我有一个嵌套对象作为状态,我在组件中有一个表单。每当用户在表单中输入内容时,我就会考虑更新状态,并避免为每个输入创建许多函数,而我正考虑使用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
}
}
}
答案 0 :(得分:6)
当然你可以使用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
}
}