我们如何部分更新状态以做出反应? [英] How do we partially update a state in react?

查看:106
本文介绍了我们如何部分更新状态以做出反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在React/React-Native中部分更新组件状态的最佳方法是什么.除了我可以使函数获取当前状态并创建新状态并合并新的{key:value}和先前的状态这一事实.例如:

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',
      } 
}

我想将last_name更新为另一个值.当我打电话 this.setState(formData:{{'last_name':newValue}}),它将formData词典重置为姓:new Value.有办法有效地做到这一点吗?

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?

推荐答案

我认为您可以尝试两种方法:

I think there are two things you could try:

  1. 点差运算符

很喜欢

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

  1. 获取当前状态的名字并重新应用:

像这样

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.

这篇关于我们如何部分更新状态以做出反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆