简体   繁体   中英

How to setState by value in React?

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

ES6简称:

this.setState({...x});

this.setState({ x });

如果你使用thingChanged函数进行双向数据绑定, LinkedStateMixin将帮助你用更少的代码完成它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM