[英]React Props do not update state
如果我直接使用父級的傳入屬性設置Switch的選中屬性,則嘗試從其父級的屬性設置嵌套組件的狀態checked={Boolean(this.props.contData.statesValue.active)}
然后開關ui成功從on變為off,
import React, { Component } from "react" import Switch from '@material-ui/core/Switch'; class Test extends Component { render() { return ( <div> <Switch checked={Boolean(this.props.contData.statesValue.active)} /> </div> ); } } export default (Test);
但是,如果我嘗試設置通過狀態檢查,則ui不會更新,並且記錄this.state.checked的值不會更改,
我冒昧猜測我在生命周期的錯誤部分更新了代碼,但是任何幫助將不勝感激
import React, { Component } from "react" import Switch from '@material-ui/core/Switch'; class Test extends Component { state = { checked:this.props.contData.statesValue.active } render() { return ( <div> <Switch checked={Boolean(this.state.checked)} /> </div> ); } } export default (Test);
該狀態最初設置為prop值,並且在收到新的prop值時不會更新。
這是getDerivedStateFromProps
生命周期方法的用途:
state = {};
static getDerivedStateFromProps(props, state) {
return {
checked: !!props.contData.statesValue.active
};
}
render() {
return (
<div>
<Switch checked={this.state.checked} />
</div>
);
}
如果狀態與道具沒有不同,則不需要狀態。 組件可以是無狀態的,而是直接使用props。
{Boolean(this.state.checked)}
將變量轉換為不再是變量的布爾值。 它獲取this.state.checked的值,將其轉換為布爾值,並且不再更新,因為它不是變量。 因此,您需要將其修改為<Switch checked={this.state.checked} />
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.