问题
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