我是React.js的新手,我努力去理解反應生命週期方法中的幾種方法。反應生命週期方法的瞭解
到目前爲止,我還是有一些讓我困惑:
1)
至於我的理解,componentWillUpdate
和componentWillReceiveProps
的區別 是,當父母改變道具和我們componentWillReceiveProps
會叫可以在componentWillReceiveProps
裏面使用setState(setState)。
例如: https://github.com/bgerm/react-table-sorter-demo/blob/master/jsx/app.jsx
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
,我們將期待componentWillReceiveProps
中的tablesorter被稱爲
不過,我不在這種情況下,不太瞭解如何使用componentWillUpdate
,012的定義是
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");
});
},
項目將首先推翻,爲什麼我們仍然需要 items: this.props.initialItems || []
的int getInitialState方法?
希望你能理解我的解釋,並請給我一些提示,如果你有任何。非常感謝:)
nextState不會得到來自父母傳給孩子。 –