提取数据后,异步响应渲染组件

时间:2018-07-27 11:25:59

标签: javascript reactjs

获取数据后,我需要呈现一个组件。如果尝试立即加载数据,则会渲染组件,但不会显示任何数据。

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

2 个答案:

答案 0 :(得分:1)

您可以使用短路来做到这一点。

(gdb) run

答案 1 :(得分:1)

您可以保留另一个状态,例如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>
    );
  }
}
相关问题