如果我直接使用父 checked={Boolean(this.props. contData.statesValue.active)}
然后 switch 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);
最佳答案
{Boolean(this.state.checked)}
将变量转换为不再是变量的 bool 值。它获取 this.state.checked 的值,将其转换为 bool 值并且不再更新它,因为它不是变量。所以你需要将其修改为 <Switch checked={this.state.checked} />
相反。
关于javascript - React Props 不更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54776046/