最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React render component asynchronously, after data is fetched - Stack Overflow

programmeradmin6浏览0评论

I need to render a ponent after data is fetched. If try to load data instantly, ponent 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));
  };

  ponentDidMount() {
    this.getGames();
  }

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

I need to render a ponent after data is fetched. If try to load data instantly, ponent 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));
  };

  ponentDidMount() {
    this.getGames();
  }

  render() {
    return (
      <div className="App">
        <Game gameId={this.state.links[0].id} /> //need to render this part
        after data is received.
      </div>
    );
  }
}
Share Improve this question edited Jul 27, 2018 at 11:26 Tholle 113k22 gold badges208 silver badges197 bronze badges asked Jul 27, 2018 at 11:25 EfkissEfkiss 1154 silver badges11 bronze badges 1
  • You need to rerender it actually, right? – Abin Thaha Commented Jul 27, 2018 at 11:28
Add a ment  | 

3 Answers 3

Reset to default 4

You could keep an additional piece of state called e.g. isLoading, and render null until your network request has finished.

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

  ponentDidMount() {
    this.getGames();
  }

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

    if (isLoading) {
      return null;
    }

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

You can do like this using short circuit.

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

Can we use the pattern of "Render-as-you-fetch" to solve the problem. Using a flag to check whether loading is plete doesn't look like a clean solution..

发布评论

评论列表(0)

  1. 暂无评论