小编典典

嵌套对象的setState

reactjs

我有一个嵌套对象作为状态,并且在组件中有一个表单。我正在考虑每次用户在表单中输入内容时都要更新状态,并避免为每个输入创建很多功能,我正在考虑使用switch创建一个功能。

  1. 使用switch创建单个功能是个好主意吗?
  2. 如何更新对象的单个嵌套元素?

我已经尝试使用以下代码,但无法正常工作:

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
    }

  }
}

阅读 348

收藏
2020-07-22

共1个答案

小编典典

当然,您可以使用switch,AFAIK没错。

并使用来更新嵌套对象setState。看例子

  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
    }

  }
2020-07-22