我是React.js的新手,正在努力理解React生命周期方法中的一些方法。
到目前为止,有一些让我困惑的东西:
1)
据我所知,componentWillUpdate
和componentWillReceiveProps
之间的区别在于当父组件更改props时,componentWillReceiveProps
将被调用,我们可以使用setState(在componentWillReceiveProps
内设置此子级的setState)。
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>
);
}
});
在TableSorter中,我们有:
componentWillReceiveProps: function(nextProps) {
// Load new data when the dataSource property changes.
if (nextProps.dataSource != this.props.dataSource) {
this.loadData(nextProps.dataSource);
}
}
当我们改变this.state.source
时,我们期望TableSorter
中的componentWillReceiveProps
被调用。
然而,在这种情况下我不太明白如何使用componentWillUpdate
,componentWillUpdate
的定义是:
componentWillUpdate(object nextProps, object nextState)
怎样将父组件的nextState传递给子组件?或者我理解错了,是从父元素中传递的nextState吗?
2) componentWillMount
方法让我感到困惑,因为在官方文档中,它说:
在初始渲染之前,在客户端和服务器上都会被调用一次。
在这种情况下,如果我在此方法中使用setState,则它将覆盖getInitialState,因为它仅在最初被调用一次。在这种情况下,设置getInitialState方法中的参数的原因是什么。在这个特定的例子中,我们有:
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");
});
},
项目将被首先覆盖,为什么我们仍然需要在getInitialState方法中使用items: this.props.initialItems || []
?
希望您可以理解我的解释,如果有任何提示,请告诉我。