I am new to React.js and am trying very hard to understand a few methods in the React lifecycle methods.
So far I have something that bothers me:
one)
As far as I understand, the difference between componentWillUpdate and componentWillReceiveProps is that componentWillReceiveProps will be called when the parent changes props, and we can use setState (setState of this descendant inside componentWillReceiveProps ).
for example: reaction-table-sorter-demo
var App = React.createClass({ getInitialState: function() { return {source: {limit: "200", source: "source1"}}; }, handleSourceChange: function(source) { this.setState({source: source}); }, render: function() { return ( <div> <DataSourceSelectors onSourceChange={this.handleSourceChange} source={this.state.source} /> <TableSorter dataSource={urlForDataSource(this.state.source)} config={CONFIG} headerRepeat="5" /> </div> ); } });
In TableSorter we have
componentWillReceiveProps: function(nextProps) { // Load new data when the dataSource property changes. if (nextProps.dataSource != this.props.dataSource) { this.loadData(nextProps.dataSource); } }
That is, when we change this.state.source , we expect componentWillReceiveProps be called in TableSorter.
However, I do not quite understand how to use componentWillUpdate in this case, the definition of componentWillUpdate is
componentWillUpdate(object nextProps, object nextState)
How can we pass nextState from parent to child? Or maybe I'm wrong, is nextState passed from the parent element?
2) the componentWillMount method confuses me because the official documentation says that
Called once, both on the client and on the server, immediately before the initial rendering occurs.
In this case, if I use setState in this method, it will override getInitialState, since it will only be called once from the beginning. In this case, what is the reason for setting the parameters in the getInitialState method. In this particular case, we have:
getInitialState: function() { return { items: this.props.initialItems || [], sort: this.props.config.sort || { column: "", order: "" }, columns: this.props.config.columns }; }, componentWillMount: function() { this.loadData(this.props.dataSource); }, loadData: function(dataSource) { if (!dataSource) return; $.get(dataSource).done(function(data) { console.log("Received data"); this.setState({items: data}); }.bind(this)).fail(function(error, a, b) { console.log("Error loading JSON"); }); },
elements will be redefined initially and why do we still need items: this.props.initialItems || [] items: this.props.initialItems || [] in the getInitialState method?
Hope you understand my explanation, and please give me some advice if you have any.