首页 > 解决方案 > 当在 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;
 }

任何示例或更好的做法都会有所帮助。谢谢

标签: reactjsweb-frontend

解决方案


你可以试试这个

  this.setState(prevState => ({
    mainValue: {
       ...prevState.mainValue,
      cellular: value
  }}))

这是一种更新状态的不可变方式。


推荐阅读