ReactJS async, wait for results

前端 未结 2 1066
青春惊慌失措
青春惊慌失措 2020-12-30 00:17

I am new to ReactJS and trying to understand it. Now I have a situation where I am loading information needed for rendering. But as it is asynchronous the component renders

相关标签:
2条回答
  • 2020-12-30 01:02

    ComponentDidMount Lifecycle Method

    According to the docs, componentDidMount is the component hook you should be using to do your ajax request:

    http://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount

    ComponentDidMount

    Invoked immediately after rendering occurs... If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval, or send AJAX requests, perform those operations in this method.

    Example

    Using your example, the code might look like this:

    var InfoPage = React.createClass({
      getInitialState: function () {
        return { info: {} };
      },
    
      componentDidMount: function () {
        $.ajax({
          url: '/info.json',
          dataType: 'json',
          success: function(data) {
            this.setState({info: data});
          }.bind(this)
        });
      },
    
      render: function() {        
        return (
          <div>info: {this.state.info}</div>            
        );
      }
    });
    

    getInitialState

    Above, we are using the getInitialState method to return an empty info object. This allows our component to render, while we wait for the server to return with data.

    Once componentDidMount executes, it will use this.setState to replace the empty info and the server data and re-render the component.

    Further reading

    You can see this approach used in in the Updating state section of the React tutorial.

    0 讨论(0)
  • 2020-12-30 01:09

    You need to do something like below:

    var InfoPage = React.createClass({
      getInitialState: function() {
         return {info: "loading ... "};
      },
      componentDidMount: function() {
         this.getInfo();
      },
      render: function() {        
        return (
            <div>info: {this.state.info}</div>            
        );
      },
      getInfo:function(){
         $.ajax({ url:"restapi/getInfo/whatever", .... }).success(function(res){
            this.setState({info:res});
         }.bind(this));
      }
    });
    
    0 讨论(0)
提交回复
热议问题