How do we partially update a state in react?

风流意气都作罢 提交于 2019-12-19 04:06:07

问题


I was wondering what is the best way to partially update a state of a component in React/React-Native. Other than the fact that I can make a function which takes the current state and creates a new state and merges the new {key:value} and the previous state. For example:

{
      dataStream:[//having data here], 
      formData: {
         'first_name': 'Richard',
         'last_name' : 'Barbieri',
      } 
}

I want to update last_name to another value. When I call this.setState(formData:{{'last_name':newValue}}), it resets the formData dictionary to just last name: new Value. Is there a way to this efficiently?


回答1:


I think there are two things you could try:

  1. Spread operator:

this.setState({formData: {...this.state.formData, "last_name" : newValue } });

or

  1. Take current state's first_name and reapply it:

this.setState({ formData: { "first_name": this.state.formData.first_name, "last_name" : newValue } })

I'm not too sure about the first one, but I think the second one should work.




回答2:


What happens is normal because you reassign the whole forData.

If you want to add something to the existing form data do something like that (there are plenty of other solutions ^^)

this.setState({
    formData: Object.assign(this.state.formData, { 'last_name': newValue } 
})


来源:https://stackoverflow.com/questions/42898468/how-do-we-partially-update-a-state-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!