[英]Updating a child component after the parent state changes
componentWillReceiveProps現在已過時,它將很快被刪除。
那么,當父級需要獲取一些數據時,更新子級組件的最干凈方法是什么?
有關更多詳細信息,請參見舊問題。
謝謝
更新:
基本上,父組件會獲取一些數據,而子組件則需要該數據。
這是子組件。
class Dropdown extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
// This is deprecated so need to be replaced by your answer
componentWillReceiveProps(nextProps) {
this.setState({
value: nextProps._layouts[0]
});
}
handleChange(event) {
this.setState({
value: event.target.value
});
}
render() {
// The options for the dropdown coming from the parent
const options = this.props._layouts.map((number) =>
React.createElement("option", null, number)
)
// This logs the value coming from the parent
// A timeout is needed since fetch is asynchronous
setTimeout(() => {
console.log(this.state.value)
}, 400);
// This is just a dropdown menu
return React.createElement("div",
null, React.createElement("span", {
class: "custom-dropdown"
}, React.createElement("select", {
onChange: this.handleChange,
}, options)));
}
}
您可以使用shouldComponentUpdate(nextProps,nextState)
並在父項中的props
或state
更改時返回true
。
替換componentWillReceiveProps
的生命周期方法是static getDerivedStateFromProps
。 (實際上這並不完全正確,但是您可以用它達到相同的結果)
該函數是靜態的,並接收組件的狀態和屬性,並返回一個新對象以合並到組件的狀態。
但是真正的問題是-您真的需要嗎? 上面問題的答案(略有調整):
getDerivedStateFromProps(nextProps) {
return nextProps.data;
}
根本什么也沒做。 您也可以使用道具代替狀態。
正如React文檔所說:
此方法適用於狀態依賴於道具隨時間變化的罕見用例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.