简体   繁体   English

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

[英]React render component asynchronously, after data is fetched

I need to render a component after data is fetched.获取数据后,我需要渲染一个组件。 If try to load data instantly, component gets rendered but no data is show.如果尝试立即加载数据,组件会被渲染但没有数据显示。

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

You can do like this using short circuit. 您可以使用短路来做到这一点。

{
  this.state.links && <Game gameId={this.state.links[0].id} />
}

You could keep an additional piece of state called eg isLoading , and render null until your network request has finished. 您可以保留一个称为isLoading的附加状态,并在您的网络请求完成之前将其呈现为null

Example

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

Can we use the pattern of "Render-as-you-fetch" to solve the problem.我们可以使用“Render-as-you-fetch”的模式来解决这个问题吗? Using a flag to check whether loading is complete doesn't look like a clean solution..使用标志来检查加载是否完成看起来不像是一个干净的解决方案..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM