我有一个嵌套对象作为状态,我有一个组件中的表单。我在考虑每次用户在表单中输入内容时更新状态,并且为了避免为每个输入创建许多函数,我在考虑使用 switch 创建一个函数。
- 使用 switch 创建单个函数是个好主意吗?
- 如何更新对象的单个嵌套元素?
我试过下面的代码,但它不起作用:
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
}
}
}
最佳答案
当然你可以使用 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
}
}
关于javascript - 嵌套对象的 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44118037/