【问题标题】:Accessing JSON Array Data in React.js/Next.js Combo在 React.js/Next.js 组合中访问 JSON 数组数据
【发布时间】:2020-05-29 05:21:00
【问题描述】:

给定一个返回 JSON 数据的 API,例如:

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

数组的长度未知。

我正在通过 isomorphic-fetch 获取数据,如下所示:

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

正在工作(console.log.stringify(data))。

现在我想在我的 displayPosts 页面上显示这些帖子。 因此我正在使用以下 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 页面中的每个帖子

<Posts posts={props.Posts}/>

?

【问题讨论】:

    标签: reactjs api next.js


    【解决方案1】:
    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
             });
         }
      }
    

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-12-21
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 2023-02-04
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多