How to update nested state properties in React

后端 未结 26 1958
野趣味
野趣味 2020-11-21 06:35

I\'m trying to organize my state by using nested property like this:

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

But updating

26条回答
  •  囚心锁ツ
    2020-11-21 07:18

    This is my initialState

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

    The hook or you can replace it with the state (class component)

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

    The method for handleChange

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

    Method for set state with nested states

    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;
    }
    

    Finally this is the input that I use

    
    

提交回复
热议问题