Reputation: 47609
Is there a simpler way to update state if I have the name of the attribute? Something simpler than this:
function thingChanged(name, value) {
var x = {};
x[name] = value;
this.setState(x)
}
Upvotes: 3
Views: 328
Reputation: 2978
If you're using the thingChanged
function for two-way data binding the LinkedStateMixin will help you do it with less code.
Upvotes: 0
Reputation: 5262
ES6 shorthands:
this.setState({...x});
this.setState({ x });
Upvotes: 2
Reputation: 108480
It’s not exactly shorter but this should work:
function thingChanged(name, value) {
this.setState(Object.defineProperty({}, name, {value:value}))
}
Upvotes: 2
Reputation: 32785
It is not possible to further reduce the code with the current ECMAScript version. Perhaps with ES6 it might be possible, depending on what features will the language have.
However if you're worried about code redundancy, you can add that method to a mixing and refer it in all components that you need to.
Update: Thanks to @FakeRainBrigand for providing the ES6 syntax that allows the code reduction: setState({[name]: value});
Upvotes: 3