setState for nested objects

后端 未结 1 1553
耶瑟儿~
耶瑟儿~ 2021-02-04 22:51

I have a nested object as a state and I have a form in a component. I was thinking of updating the state every time the user enter something in the form and to avoid creating ma

相关标签:
1条回答
  • 2021-02-04 23:01

    Of course you can use switch, Nothing wrong AFAIK.

    And to update nested objects with setState. See the example

      updatePreferences = (preferenceName, enteredValue) => {
         switch (preferenceName) {
          case preferenceName === "minutes":
            this.setState({minutes: enteredValue});
            return
          case preferenceName === "business":
            this.setState({...this.state, interests: {
              ...this.state.interests,
              business: !this.state.interests.business
            }});
            return
          default:
            return
        }
    
      }
    
    0 讨论(0)
提交回复
热议问题