问题
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.
- Is creating a single function with switch a good idea?
- 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