在 React.js/Next.js 组合中访问 JSON 数组数据

Accessing JSON Array Data in React.js/Next.js Combo

给定 API 其中 returns JSON 数据如下:

["posts": 
    {"id":1,
     "name":"example",
     "date":"exampledate",
     "content":"examplecontent",
     "author":"exampleauthor"},
    {"id":2,
 ..]

数组的长度未知。

我正在像这样通过同构获取获取数据:

displayPosts.getInitialProps = async function() {
const res = await fetch('.../post');
const data = await res.json();
  return{
    posts: data.posts
  }
}

正在工作(console.log.stringify(数据))。

现在我想在我的 displayPosts 页面上显示这样的 post。 因此,我正在使用以下 React 组件。

class Posts extends React.Component {
  stat = {
  // here i don't know how to set the state
}

  render() {
    return (
      // i want to render the data here
    );
  }
}

导出默认帖子;

问题: 我如何设置状态,以便我可以在 displayPosts.js 页面中用

整齐地显示每个 post
<Posts posts={props.Posts}/>

?

class Posts extends React.Component {
  state = {
      posts: []
  }

  componentDidMount() {
      this.savePosts();
  }

  componentDidUpdate() {
      this.savePosts();
  }

  savePosts = () => {
      if(this.props.posts){
         //do any other processing here first if you like
         this.setState({
             posts: this.props.posts
         });
     }
  }

您可能不需要将帖子保存在状态中,因为您可以直接从道具中提取它们。但如果您需要以某种方式处理或转换它们,它可能有意义。

在任何一种情况下,您只需挂接到生命周期方法即可。

注意:这将在每次组件更新时设置状态。通常您只想在特定道具更改时更新状态。如果是这样,您可以先比较新旧道具,看看它是否以某种方式发生了变化,这意味着您想要更新您的状态。