简体   繁体   English

具有动态键值的Reactjs @setState

[英]Reactjs @setState with a dynamic key value

I have a dynamic object in props, which I want to send in state 我在道具中有一个动态物体,我想在状态下发送

@setState
  key: val
  values:
    another_key: value
    @props.data.option: @props.data.value

But this way does not work, I found this solution: 但是这种方式不起作用,我找到了这个解决方案:

  newState = {}
  newState[@props.data.option] = @props.data.value
  this.setState(newState);

But this way sets the value of the right in state 但是这种方式设置了状态权的价值

The issue here is that you are dealing with nested objects in state, and the entire object values is replaced when it seems you only want to update a subset of the keys in the values object. 这里的问题是,你正在处理状态嵌套的对象,整个对象values时,似乎你只需要在更新密钥的一个子集被替换values对象。 The best way to do this is to use React's immutability helpers via the set operation. 最好的方法是通过set操作使用React的不变性助手。 ( https://facebook.github.io/react/docs/update.html ). https://facebook.github.io/react/docs/update.html )。

using es6, you can set a dynamic key: 使用es6,您可以设置动态密钥:

var update = require('react-addons-update');

var newState = update(this.state, {
  values:  {[dynamic_key]: {$set: dynamic_value}}
});

this.setState(newState);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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