Using computed value for sub key with React setState

时光怂恿深爱的人放手 提交于 2021-02-19 06:38:04

问题


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 });

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 });

回答1:


If you want to overwrite the old properties in foo:

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

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
    }
  }
});

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})
  }
});


来源:https://stackoverflow.com/questions/52225909/using-computed-value-for-sub-key-with-react-setstate

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