React fetch data in server before render

前端 未结 8 1816
自闭症患者
自闭症患者 2020-12-02 18:29

I\'m new to reactjs, I want to fetch data in server, so that it will send page with data to client.

It is OK when the function getDefaultProps return dummy data like

相关标签:
8条回答
  • 2020-12-02 19:10

    As a supplement of the answer of Michael Parker, you can make getData accept a callback function to active the setState update the data:

    componentWillMount : function () {
        var data = this.getData(()=>this.setState({data : data}));
    },
    
    0 讨论(0)
  • 2020-12-02 19:11

    What you're looking for is componentWillMount.

    From the documentation:

    Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call setState within this method, render() will see the updated state and will be executed only once despite the state change.

    So you would do something like this:

    componentWillMount : function () {
        var data = this.getData();
        this.setState({data : data});
    },
    

    This way, render() will only be called once, and you'll have the data you're looking for in the initial render.

    0 讨论(0)
提交回复
热议问题