How can I remove an attribute from a Reactjs component's state object

后端 未结 10 2066
南笙
南笙 2020-12-06 09:17

If I have a react component that had a property set on it\'s state:

onClick() {
    this.setState({ foo: \'bar\' });
}

Is it possible to re

10条回答
  •  一个人的身影
    2020-12-06 09:51

    Only way is to create a deep copy and then delete that property from the deep clone and return the deep clone from the setState updater function

    this.setState(prevState => {
                const newState = {
                  formData: {
                    ...prevState.formData,
                    document_details: {
                      ...prevState.formData.document_details,
                      applicant: {
                        ...prevState.formData?.document_details?.applicant
                        keyToBeDeleted: dummVAlue //this is redundant
                      }
                    }
                  }
                };
                delete newState.formData.document_details.applicant.keyToBeDeleted;
                return newState;
              });
    

提交回复
热议问题