我试图通过使用这样的嵌套属性来组织我的状态:

this.state = {
   someProperty: {
      flag:true
   }
}

但是像这样更新状态,

this.setState({ someProperty.flag: false });

是行不通的。怎样才能正确地做到这一点呢?


当前回答

There is another option and this works if there are multiple items in the list of objects: copy the object using this.state.Obj to a variable (say temp), use filter() method to traverse through the object and grab the particular element you want to change into one object(name it updateObj) and the remaining list of object into another object(name this as restObj). Now edit the contents of object you want to update creating a new item (say newItem). Then call this.setUpdate() and use spread operators to assing new list of objects to the parent object.

this.state = {someProperty: { flag:true, }}


var temp=[...this.state.someProperty]
var restObj = temp.filter((item) => item.flag !== true);
var updateObj = temp.filter((item) => item.flag === true);

var newItem = {
  flag: false
};
this.setState({ someProperty: [...restObj, newItem] });

其他回答

这是我的initialState

    const initialStateInput = {
        cabeceraFamilia: {
            familia: '',
            direccion: '',
            telefonos: '',
            email: ''
        },
        motivoConsulta: '',
        fechaHora: '',
        corresponsables: [],
    }

钩子或者你可以用状态(类组件)替换它

const [infoAgendamiento, setInfoAgendamiento] = useState(initialStateInput);

handleChange的方法

const actualizarState = e => {
    const nameObjects = e.target.name.split('.');
    const newState = setStateNested(infoAgendamiento, nameObjects, e.target.value);
    setInfoAgendamiento({...newState});
};

使用嵌套状态设置状态的方法

const setStateNested = (state, nameObjects, value) => {
    let i = 0;
    let operativeState = state;
    if(nameObjects.length > 1){
        for (i = 0; i < nameObjects.length - 1; i++) {
            operativeState = operativeState[nameObjects[i]];
        }
    }
    operativeState[nameObjects[i]] = value;
    return state;
}

最后这是我使用的输入

<input type="text" className="form-control" name="cabeceraFamilia.direccion" placeholder="Dirección" defaultValue={infoAgendamiento.cabeceraFamilia.direccion} onChange={actualizarState} />

创建一个状态的副本:

let someProperty = JSON.parse(JSON.stringify(this.state.someProperty))

对该对象进行更改:

someProperty.flag = "false"

现在更新状态

this.setState({someProperty})

试试下面的代码:

this.setState({ someProperty: {flag: false} });

这显然不是正确或最好的方法,但在我看来,这是更清晰的:

this.state.hugeNestedObject = hugeNestedObject; 
this.state.anotherHugeNestedObject = anotherHugeNestedObject; 

this.setState({})

然而,React本身应该迭代思想嵌套对象,并相应地更新状态和DOM。

使用箭头函数代替,这应该做的把戏。

setItems((prevState) => {
   prevState.nestedData = newNestedData;
   prevState.nestedData1 = newNestedData1;
});

不要忘记使用箭头函数(prevState) =>{更新js赋值语句…}