2015-04-26 44 views
42

我是React.js的新手,我努力去理解反應生命週期方法中的幾種方法。反應生命週期方法的瞭解

到目前爲止,我還是有一些讓我困惑:

1)

至於我的理解,componentWillUpdatecomponentWillReceiveProps的區別 是,當父母改變道具和我們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方法?

希望你能理解我的解釋,並請給我一些提示,如果你有任何。非常感謝:)

+1

nextState不會得到來自父母傳給孩子。 –

回答

51

1)componentWillReceiveProps在React更新生命週期中的componentWillUpdate之前被調用。您正確的componentWillReceiveProps可讓您撥打setState。另一方面,componentWillUpdate是您需要響應狀態更改時使用的回調。

道具和狀態之間的根本區別在於狀態是組件的私有狀態。這就是爲什麼父組件或任何其他人都不能操縱組件的狀態(例如調用setState)。因此,對於親子組件關係的默認工作流將是以下幾點:

  • 家長通過新道具給孩子
  • 孩子「componentWillReceiveProps」處理新的道具,呼籲setState如有必要
  • 兒童把手'componentWillUpdate'中的新狀態 - 但是如果你的組件是有狀態的,那麼在'componentWillReceiveProps'中處理道具就足夠了。

2)您提供了一個很好的代碼示例來說明不同之處。在getInitialState中設置的默認值將用於初始渲染。來自componentWillMountloadData調用將啓動一個AJAX請求,該請求可能會成功也可能不會成功,而且不知道需要多長時間才能完成。當AJAX請求完成並且以新狀態調用setState時,組件將使用默認值呈現在DOM中。這就是爲什麼在getInitialState中提供默認狀態的原因。

注:我發現Understanding the React Component Lifecycle文章對理解React的生命週期方法有很大的幫助。

相關問題