[英]What is the purpose of having functions like componentWillMount in React.js?
我最近在React.js中編寫組件。 我從來沒有使用過componentWillMount
和componentDidMount
類的方法。
render
是不可或缺的。 我寫的getInitialState
和其他幫助方法也派上用場了。 但不是前面提到的兩種生命周期方法。
我目前的猜測是它們用於調試? 我可以在其中調用console.log:
componentWillMount: function() {
console.log('component currently mounting');
},
componentDidMount: function() {
console.log('component has mounted');
}
還有其他用途嗎?
如果要使用某些非React JavaScript插件, componentDidMount
非常有用。 例如,React中缺少一個好的日期選擇器。 Pickaday是美麗的,它只是簡單的開箱即用。 所以我的DateRangeInput組件現在使用Pickaday作為開始和結束日期輸入,我把它連接起來如下:
componentDidMount: function() {
new Pikaday({
field: React.findDOMNode(this.refs.start),
format: 'MM/DD/YYYY',
onSelect: this.onChangeStart
});
new Pikaday({
field: React.findDOMNode(this.refs.end),
format: 'MM/DD/YYYY',
onSelect: this.onChangeEnd
});
},
需要為Pikaday呈現DOM以連接它,並且componentDidMount
鈎子允許您掛鈎到該確切事件。
如果要在組件安裝之前以編程方式執行某些操作, componentWillMount
非常有用。 我正在研究的一個代碼庫中的一個例子是一個mixin,它有一堆代碼,否則它們將被復制到許多不同的菜單組件中。 componentWillMount
用於設置一個特定共享屬性的狀態。 可以使用componentWillMount
另一種方法是通過prop(s)設置組件分支的行為:
componentWillMount() {
let mode;
if (this.props.age > 70) {
mode = 'old';
} else if (this.props.age < 18) {
mode = 'young';
} else {
mode = 'middle';
}
this.setState({ mode });
}
componentDidMount
僅在客戶端運行一次。 這很重要,特別是如果您正在編寫同構應用程序(在客戶端和服務器上運行)。 您可以使用componentDidMount執行要求您有權訪問窗口或DOM的任務。
來自Facebook的React Page
If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval, or send AJAX requests, perform those operations in this method.
componentWillMount
具有較少的用例(我實際上並沒有使用它),但它的不同之處在於它在客戶端和服務器端都運行。 您可能不希望在此處放置事件偵聽器或DOM操作,因為它將嘗試無緣無故地在服務器上運行。
這是使用componentWillMount
的同構Web應用程序的示例: https : //github.com/coodoo/react-redux-isomorphic-example
但是,我99%肯定它在服務器端沒有任何理由運行componentWillMount
的代碼(我認為使用componentDidMount
確保它只是運行客戶端會更有意義)作為確保獲取承諾的代碼是在呈現頁面之前實現的是在server.js中不在單個組件內部。
這里有關於每個組件異步提取的討論: https : //github.com/facebook/react/issues/1739據我所知,就同構性至少而言, componentWillMount
沒有一個好的用例。
在我的項目中,這是一個儀表板工具,我使用了componentDidMount()。
在主頁上,以前保存的儀表板顯示在側欄上。 我在組件呈現主頁的componentDidMount()中進行ajax調用,以便在呈現頁面后異步獲取儀表板列表。
為什么反應生命周期方法?
打算將第三方(Ex D3.js)庫與React Component一起使用
class Example extends React.component{
constructor(){
// init state
// will be called only once
}
componentWillMount(){
// will be called only once
// will not be triggered when re-rendering
// usually will fetch data that is needed in order
// to render properly from other API
}
shouldComponentUpdate(){
return false
// will not re-render itself after componentDidMount(){}
}
render(){
return (
<div id="chart"></div>
)
}
componentDidMount(){
d3.select(".chart")
.selectAll("p")
// d3.js ........
// d3.js ........
// Usually, this will trigger React to re-render itself,
// but this time will not because we have set
// shouldComponentUpdate to false
}
}
為什么React想要這樣做?
由於渲染DOM是一項昂貴的操作,因此React使用虛擬DOM層來僅更新與先前狀態不同的DOM / DOM。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.