将异步数据加载到React组件

时间:2019-03-10 23:07:18

标签: reactjs asynchronous async-await

我需要异步地将外部数据加载到我的React组件中。 The documentation here provides the following code example.

// After
class ExampleComponent extends React.Component {
  state = {
    externalData: null,
  };

  componentDidMount() {
    this._asyncRequest = loadMyAsyncData().then(
      externalData => {
        this._asyncRequest = null;
        this.setState({externalData});
      }
    );
  }

  componentWillUnmount() {
    if (this._asyncRequest) {
      this._asyncRequest.cancel();
    }
  }

  render() {
    if (this.state.externalData === null) {
      // Render loading state ...
    } else {
      // Render real UI ...
    }
  }
}

但是loadMyAsyncData()看起来像是“可以”的样子?我想它可能会使用async/await

有人可以提供例子吗?

0 个答案:

没有答案