What's the best alternative to update nested React state property with setState()?

后端 未结 4 1308
甜味超标
甜味超标 2021-02-08 08:45

I\'ve been thinking about what would be the best way among these options to update a nested property using React setState() method. I\'m also opened to more efficient methods co

4条回答
  •  既然无缘
    2021-02-08 09:26

    I can think of a few other ways to achieve it.

    Deconstructing every nested element and only overriding the right one :

    this.setState(prevState => ({
        inputs: {
            ...prevState.inputs,
            username: {
                ...prevState.inputs.username,
                touched: true
            }
        }
    }))
    

    Using the deconstructing operator to copy your inputs :

    this.setState(prevState => {
        const inputs = {...prevState.inputs};
        inputs.username.touched = true;
        return { inputs }
    })
    

    EDIT

    First solution using computed properties :

    this.setState(prevState => ({
        inputs: {
            ...prevState.inputs,
            [field]: {
                ...prevState.inputs[field],
                [action]: value
            }
        }
    }))
    

提交回复
热议问题