反应 - setState 找到 object 项目然后分配
react - setState find object item then assign
我有 object 状态 -
this.state = {
states: {
na: 0, s1a: 0, s2a: 0, s3a: 0, s4a: 0, l1a: 0, l2a: 0, l3a: 0, t1a: 0, t2a: 0, t3a: 0,
nb: 0, s1b: 0, s2b: 0, s3b: 0, s4b: 0, l1b: 0, l2b: 0, l3b: 0, t1b: 0, t2b: 0, t3b: 0
},
我想在我的函数中更改某些键的值 -
onInputUpdated(id){
var array = {};
let char = id.slice(-1);
switch(char){
case 'a':
array[id] = this.getY(ReactDOM.findDOMNode(this.refs[id].refs.inp).value);
break;
case 'b':
array[id] = this.getX(ReactDOM.findDOMNode(this.refs[id].refs.inp).value);
break;
}
this.setState({
states: { id : array[id]}
});
但是没有id,id代表字符串'na'或者其他...那我该怎么做呢?有什么建议吗?顺便说一句 onIputUpdated(id) 是来自 children..
的回调
首先,您不能直接更新嵌套状态。您将必须更新整个 "states" 对象。像这样
let oldStates = this.state.states;
oldStates[id] = array[id];
this.setState({
states: {
...oldStates
}
});
我有 object 状态 -
this.state = {
states: {
na: 0, s1a: 0, s2a: 0, s3a: 0, s4a: 0, l1a: 0, l2a: 0, l3a: 0, t1a: 0, t2a: 0, t3a: 0,
nb: 0, s1b: 0, s2b: 0, s3b: 0, s4b: 0, l1b: 0, l2b: 0, l3b: 0, t1b: 0, t2b: 0, t3b: 0
},
我想在我的函数中更改某些键的值 -
onInputUpdated(id){
var array = {};
let char = id.slice(-1);
switch(char){
case 'a':
array[id] = this.getY(ReactDOM.findDOMNode(this.refs[id].refs.inp).value);
break;
case 'b':
array[id] = this.getX(ReactDOM.findDOMNode(this.refs[id].refs.inp).value);
break;
}
this.setState({
states: { id : array[id]}
});
但是没有id,id代表字符串'na'或者其他...那我该怎么做呢?有什么建议吗?顺便说一句 onIputUpdated(id) 是来自 children..
的回调首先,您不能直接更新嵌套状态。您将必须更新整个 "states" 对象。像这样
let oldStates = this.state.states;
oldStates[id] = array[id];
this.setState({
states: {
...oldStates
}
});