首页 > 解决方案 > 获取数据后,异步响应渲染组件

问题描述

获取数据后,我需要渲染一个组件。如果尝试立即加载数据,组件会被渲染但没有数据显示。

class App extends React.Component {
  //typical construct

  getGames = () => {
    fetch(Url, {})
      .then(data => data.json())
      .then(data => {
        this.setState({ links: data });
      })
      .catch(e => console.log(e));
  };

  componentDidMount() {
    this.getGames();
  }

  render() {
    return (
      <div className="App">
        <Game gameId={this.state.links[0].id} /> //need to render this part
        after data is received.
      </div>
    );
  }
}

标签: javascriptreactjs

解决方案


您可以保留一个名为 eg 的附加状态,并在您的网络请求完成之前isLoading进行渲染。null

例子

class App extends React.Component {
  state = { links: [], isLoading: true };

  getGames = () => {
    fetch(Url, {})
      .then(data => data.json())
      .then(data => {
        this.setState({ links: data, isLoading: false });
      })
      .catch(e => console.log(e));
  };

  componentDidMount() {
    this.getGames();
  }

  render() {
    const { links, isLoading } = this.state;

    if (isLoading) {
      return null;
    }

    return (
      <div className="App">
        <Game gameId={links[0].id} />
      </div>
    );
  }
}

推荐阅读