2017-08-08 24 views
1

我是React的新手,因此我试图学习基本概念。将获取的JSON数据设置为状态并使用它

我通过API获取数据我存了一些数据转化为学习的目的,具有像这样为获取请求:

componentDidMount() { 
    fetch("myserver.com/api/a/1") 
    .then(function(response) { 
     response.json() 
    }) 
} 

,在我的构造函数中我设置状态数据:“假”:

constructor(props) { 
    super(props) 

    this.state = {data: 'false'}; 
} 

但是从这里开始我就迷路了。我通过API获取JSON对象中的三个不同字符串,但我不知道如何访问它们。我已经尝试在componentDidMount中设置setState,但我遇到了大量的错误。

在这样的情况下你会怎么做?我应该在哪里设置状态,以及您通常如何访问/遍历JSON对象?

在此先感谢!

回答

2

尝试这样:

 export default class YourComponent extends React.Component { 

     constructor(props) { 
      super(props) 

      this.state = {data: 'false'}; 
     } 

     componentDidMount() { 
       this._getData(); 
     } 


     _getData =() => { 
       fetch("myserver.com/api/a/1") 
       .then(response => { 
        if (response.ok) { 
        return response; 
       } else { 
       let errorMessage = 
        `${response.status(${response.statusText})`, 
        error = new Error(errorMessage); 
        throw(error); 
       } 
       }) 
       .then(response => response.json()) 
       .then(json =>{ 
        console.log(json); 
        this.setState({ data: json.data }) 
       }); 
      } 

      render() { 
       return (
       <div> 
        { 
        this.state.data && 
        this.state.data.map((item, key) => 
         <div key={key}> 
         {item} 
         </div> 
        )} 
       </div> 
     )} 
    } 
+0

谢谢!效果很好!我如何着手在组件中显示这些数据,即如何获取JSON对象中的项目数组? – hejhej123

+0

Eric,修改了我最简单的答案。 'map'用于数组大小写。 {key}是为了正确地重新渲染项目,项目 - 如果你的数组中有简单的东西,如果你有另一个数组,那么它将不起作用 –

+0

谢谢!这应该可行 - 很好的解释。虽然...我还在'.then(json => this.setState({data:json.data}));',错误:未处理的拒绝(TypeError):无法读取属性的数据'未定义。你有这方面的经验吗? – hejhej123

相关问题