简体   繁体   中英

Pass data from callback to React component?

I'm rendering a react component that needs data that returns asynchronously. How should I pass this to the react component when it returns from the callback?

currently in render function:

var dataToReturn; 
asynchCall(args, function(err, results) {
  dataToReturn = results;
})

return (
    <MyComponent data={dataToReturn} />
)

This of course is not working out because the data has not returned yet. If I move the render into the callback, that seems like a bad programming pattern. Is there anything in the React API meant for this use case?

thank you!

Yes, like @Fouad said:

var NewComponent = React.createClass({ 
    componentDidMount: function() {
       asynchCall(args, function(err, results) {
          this.setState({data: results});
       }.bind(this));
    },

    return (
        <MyComponent data={this.state.data} />
    )
});

Also, check out documentation page Load Initial Data via AJAX

Instead of local variables you should use this.state & this.setState which will trigger a re-render. Check out this link on fetching from the server http://facebook.github.io/react/docs/tutorial.html#fetching-from-the-server

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM