setState用于嵌套对象 [英] setState for nested objects
本文介绍了setState用于嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个嵌套对象作为状态,我在组件中有一个表单。每当用户在表单中输入内容时,我就会考虑更新状态,并避免为每个输入创建许多函数,而我正在考虑使用switch创建单个函数。
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.
- 使用switch创建单个函数是个好主意吗?
- 如何更新对象的单个嵌套元素?
我尝试使用以下代码但不起作用:
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
}
}
}
推荐答案
当然你可以使用开关
,没有错误的AFAIK。
Of course you can use switch
, Nothing wrong AFAIK.
并用<$更新嵌套对象C $ C>的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
}
}
这篇关于setState用于嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文