使用fetch在react app中渲染json数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39030239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:34:32  来源:igfitidea点击:

Using fetch to render json data in react app

jsonreactjsfetch

提问by Ash

I am trying to render some JSON about a person's location from an api in my react app.

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

I am using isomorphic-fetchto access the data from the API I can add the base test in and it correctly logs the data using below.

我正在使用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);
  });

What i'm trying to work out is how I can take this response and render it in my component which currently looks like this (in this example code below data is coming from local json file so i need to merge them together).

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

I've attempted to set up componentDidMount but could get my head around the syntax so it kept breaking, I also checked out redux actions but that exploded my brain.

我试图设置 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>
    )
}

回答by vijayst

componentDidMount should setState:

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 });
  });
}

The render component should map the state:

渲染组件应该映射状态:

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>
})