簡體   English   中英

獲取數據后,異步響應渲染組件

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

獲取數據后,我需要渲染一個組件。 如果嘗試立即加載數據,組件會被渲染但沒有數據顯示。

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

您可以使用短路來做到這一點。

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

您可以保留一個稱為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>
    );
  }
}

我們可以使用“Render-as-you-fetch”的模式來解決這個問題嗎? 使用標志來檢查加載是否完成看起來不像是一個干凈的解決方案..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM