reactjs - 当在 jsonObject 的属性上调用 setState 时,React 组件状态值未更新
问题描述
我正在研究返回布尔值的 JSON 对象的三个属性。
updateChange=(value) =>{
//Making copy of existing json Object
let newState = JSON.parse(JSON.stringify(this.state.mainValue));
// chaning property of cellular over here
newState.cellular = value;
console.log(newState);
this.setState({mainValue:newState});
//I tried setState in many different ways. But Component is not changing state value
console.log(this.state.mainValue)
};
我找到了为什么会这样。我getDerivedStateFromProps
在这个组件中使用来查看父级所做的更改以更新值。这是避免对孩子的状态进行的更改。所以我创建了一个称为先前状态的状态来比较先前的道具和从父级呈现的道具来渲染。这避免了组件在本地状态值更改时刷新。
static getDerivedStateFromProps(propsnow,state){
if(state.previous !== propsnow.detailSwitches){
return{
previous :propsnow.detailSwitches,
cellular: propsnow.detailSwitches.cellular,
wifi1: propsnow.detailSwitches.wifi1,
wifi2: propsnow.detailSwitches.wifi2
};
}
return null;
}
任何示例或更好的做法都会有所帮助。谢谢
解决方案
你可以试试这个
this.setState(prevState => ({
mainValue: {
...prevState.mainValue,
cellular: value
}}))
这是一种更新状态的不可变方式。
推荐阅读
- swift - 如何使用 WKWebView / WKHTTPCookieStore 在应用重新启动时保留 cookie
- odoo-12 - 在odoo12中将金额转换为NPR格式的单词?
- javascript - 如何使用 php 在 wordpress 中使用他们的 ID 获取所有用户状态(登录或注销)的列表
- hive - 当使用 oozie 子工作流调用 hive -e 时抛出 NoSuchMethodError
, 从主工作流调用时运行完美 - asp.net-mvc - 找不到控制器名称 .net core 2.0
- python - 更改文件夹中 csv 文件的名称
- javascript - 如何在谷歌地图中找到多边形内的所有地方
- dart - 如何修复“在 Flutter 中未获取 SignInWithgoogle 属性”
- msbuild - 如何根据主要版本安装 NuGet 包
- laravel-5.2 - 用户首次使用 Laravel PWA 成功登录时如何处理身份验证?