![](/img/trans.png)
[英]React: Using `setState` with a function inside `componentWillReceiveProps`
[英]React - setState in componentWillReceiveProps
這合法嗎?
componentWillReceiveProps: function(nextProps) {
if (typeof nextProps.contact != 'undefined') {
this.setState({forename: nextProps.contact.forename});
this.setState({surname: nextProps.contact.surname});
this.setState({phone: nextProps.contact.phone});
this.setState({email: nextProps.contact.email});
}
}
因為我不知道如何填充我的輸入,但仍然能夠用戶編輯輸入。 所以我提出了這個解決方案,而不是試圖操縱this.props。
有什么建議?
從React v16.6.3開始,這被認為是UNSAFE, componentWillReceiveProps
被標記為棄用 。 計划在版本17中進行刪除。
注意:
使用這種生命周期方法通常會導致錯誤和不一致,因此將來會被棄用。
如果您需要執行副作用(例如,數據提取或動畫)以響應props中的更改,請改用componentDidUpdate生命周期。
對於其他用例,請遵循此博客文章中有關派生狀態的建議。
如果您僅在prop更改時使用componentWillReceiveProps重新計算某些數據,請使用memoization helper。
如果您在prop更改時使用componentWillReceiveProps“重置”某些狀態,請考慮使用組件完全控制組件或完全不受控制。
在極少數情況下,您可能希望將getDerivedStateFromProps生命周期用作最后的手段。
在您的情況下,您應該使用componentDidUpdate
。
componentWillReceiveProps
存在的唯一原因是為組件提供了setState的機會。 所以,是的,你在其中同步設置的任何狀態都將與新道具一起處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.