【问题标题】:Using fetch to render json data in react app在 React 应用中使用 fetch 渲染 json 数据
【发布时间】:2016-12-26 02:17:07
【问题描述】:

我正在尝试从我的 react 应用程序中的 api 呈现一些关于某人位置的 JSON。

我正在使用 isomorphic-fetch 从 API 访问数据,我可以在其中添加基本测试,并使用下面的方法正确记录数据。

 require('isomorphic-fetch');
 require('es6-promise').polyfill();

 var url = 'http://localhost:3000/api/data'

 fetch(url)
    .then(function(response) {
    if (response.status >= 400) {
       throw new Error("Bad response from server");
    }
    return response.json();
  })
  .then(function(data) {
     console.log(data);
  });

我想要解决的是如何获取此响应并将其呈现在我的组件中,目前看起来像这样(在此示例代码中,下面的数据来自本地 json 文件,因此我需要将它们合并在一起) .

我曾尝试设置 componentDidMount,但我对语法有所了解,所以它一直在中断,我还检查了 redux 操作,但这让我大吃一惊。

const personLoc = Object.keys(data.person.loc).map((content, idx) => {
    const items = data.person.loc[content].map((item, i) => (
        <p key={i}>{item.text}</p>
    ))

    return <div key={idx}>{items}</div>
})

export default function PersonLocation() {
    return (
        <div className="bio__location">
            {personLoc}
        </div>
    )
}

【问题讨论】:

    标签: json reactjs fetch


    【解决方案1】:

    componentDidMount 应该设置状态:

    componentDidMount() {    
      var that = this;
      var url = 'http://localhost:3000/api/data'
    
      fetch(url)
      .then(function(response) {
        if (response.status >= 400) {
          throw new Error("Bad response from server");
        }
        return response.json();
      })
      .then(function(data) {
        that.setState({ person: data.person });
      });
    }
    

    渲染组件应该映射状态:

    const personLoc = Object.keys(this.state.person.loc).map((content, idx) => {
        const items = this.state.person.loc[content].map((item, i) => (
            <p key={i}>{item.text}</p>
        ))
    
        return <div key={idx}>{items}</div>
    })
    

    【讨论】:

    • 谢谢,这很有帮助 我使用扩展进行设置,但后来自动绑定出现问题,所以我设置了一个构造函数,但现在我得到Cannot read property 'bind' of undefined
    • 我设法通过绑定使其工作,然后还添加了一个检查以查看状态是否存在。
    猜你喜欢
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 2017-04-13
    • 1970-01-01
    • 2017-09-28
    相关资源
    最近更新 更多