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)
}
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});
It’s not exactly shorter but this should work:
function thingChanged(name, value) {
this.setState(Object.defineProperty({}, name, {value:value}))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With