React - 从API获取数据时,this.state在render内部为null

onu*_*rhb 5 javascript reactjs

我试图通过制作一个简单的应用程序来学习反应,我试图从服务器获取json格式的数据,然后将其渲染到视图.问题是我收到一个错误,它说this.state.data为null.我该如何解决这个问题?代码:

class App extends React.Component {

  constructor() {
    super();
    //Query data
    fetch('http://localhost:8080/api?access_token=56d847accb86bddc243d4b93')
      .then(response => response.json())
      .then((data) => {
        this.setState({
          data: data
        })

      })
      .catch(err => console.error('Error ', err.toString()));

  }

  getInitialState() {
    return {
      data: {}
    };
  }

  render() {

    return (
      <h1>{this.state.data}</h1>
      );

  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
Run Code Online (Sandbox Code Playgroud)

And*_*yco 7

使用ES6类作为组件时,不会getInitialState调用任何方法.
而是在构造函数中的实际实例上设置状态.

class App extends React.Component {

  constructor() {
    super();

    this.state = {
      data: {}
    };

    fetch('http://localhost:8080/api?access_token=56d847accb86bddc243d4b93')
      .then(response => response.json())
      .then(data => this.setState({ data }))
      .catch(err => console.error('Error ', err.toString()));

  }

  render() {
    return <h1>{this.state.data}</h1>;
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
Run Code Online (Sandbox Code Playgroud)

  • 我不一定说你不应该,而是转发React团队所倡导的最佳实践.最好的解释似乎是`componentDidMount`适用于所有副作用代码(AJAX/DOM操作/附加事件).有一篇关于它的老帖子[这里](http://stackoverflow.com/questions/27139366/why-do-the-react-docs-recommend-doing-ajax-in-componentdidmount-not-componentwi). (2认同)