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

I need to render a ponent after data is fetched. If try to load data instantly, ponent gets rendered bu

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..

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744105494a4558707.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信