在React setState中使用子键的计算值 [英] Using computed value for sub key with React setState

查看:103
本文介绍了在React setState中使用子键的计算值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在React中更新状态时为子键使用计算值.

I would like to be able to use computed values for sub keys when updating state in React.

我了解如何在这样的简单设置中使用计算值:

I understand how to use computed values in straightforward settings like this:

this.setState({ [name]: value });

但是我很难让键值计算在这种情况下起作用:

But I am having trouble getting key-value computation to work for a situation like this:

constructor(props) {
    super(props);
    this.state = {
        foo: { a: 1, b: 2 }
    }; 
}

const keyToChange = 'a';
const value = 3;

this.setState({ foo[keyToChange]: value });

我如何制作类似这样的东西

How can I make something that works like

this.setState({ foo.a: value });

但是其中a可以是计算值吗?

But where a can be a computed value?

我尝试了以下方法,但似乎不起作用:

I have tried the following, but it doesn't seem to work:

const subKeyName = 'a';

// Doesn't work
const nameOfKey = 'foo.' + subKeyName;
this.setState({ [`${nameOfKey}`]: value });

// Doesn't work
this.setState({ foo[subKeyName]: value });

推荐答案

如果要覆盖foo中的旧属性:

If you want to overwrite the old properties in foo:

this.setState({ 
  foo: {
    [keyToChange]: value 
  }
});

如果要将旧属性保留在foo中,而只需在其中添加(或替换)一个键:

If you want to keep old properties in foo but just add (or replace) one key in it:

this.setState(oldState => {
  return {
    foo: {
      ...oldState.foo,
      [keyToChange]: value
    }
  }
});

最后一个示例使用对象传播语法,这还不是javascript的标准化部分(当前此babel插件如果您现在想使用它.如果您没有该插件,则与标准javascript等效的是:

That last example is using object spread syntax, which is not yet a standardized part of javascript (currently a stage 4 proposal, so it will be part of the language soon). So you should be using this babel plugin if you want to use it at this time. If you don't have that plugin, the equivalent with standard javascript is:

this.setState(oldState => {
  return {
    foo: Object.assign({}, oldState.foo, {[keyToChange]: value})
  }
});

这篇关于在React setState中使用子键的计算值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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