使用fetch在react app中呈现json数据

时间:2016-08-19 02:29:20

标签: json reactjs fetch

我正在尝试在我的反应应用程序中从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>
    )
}

1 个答案:

答案 0 :(得分:15)

componentDidMount应该是setState:

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>
})
相关问题