setState for nested objects

情到浓时终转凉″ 提交于 2019-12-03 11:19:45

问题


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 many functions for each input I was thinking of creating a single function using switch.

  1. Is creating a single function with switch a good idea?
  2. How can I update a single nested element of the object?

I have tried with the following code but it doesn't work:

class App extends Component {
  constructor(props) {
      super(props)
      this.state = {
        minutes: null,
        interests: {
          business: false,
          code: false,
          design: false
        },
        errors: []
      }
  }

  updatePreferences = (preferenceName, enteredValue) => {
    switch (preferenceName) {
      case preferenceName === "minutes":
        this.setState({minutes: enteredValue})
        return
      case preferenceName === "business":
        this.setState({interests.business: !this.state.interests.business})
        return
      case default:
        return
    }

  }
}

回答1:


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
    }

  }


来源:https://stackoverflow.com/questions/44118037/setstate-for-nested-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!