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. The best way to do this is to use React's immutability helpers via the set
operation. ( https://facebook.github.io/react/docs/update.html ).
using es6, you can set a dynamic key:
var update = require('react-addons-update');
var newState = update(this.state, {
values: {[dynamic_key]: {$set: dynamic_value}}
});
this.setState(newState);
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.