React - 将数组推送到状态

React - Push array to State

getInitialState: function() {
     p:{'Keeper' : [] , 'Defenders': [] , 'Midfield' : [], 'Forwards' : []}}
}
onUpdatePlayers : function (newState) {
    var pos;

    if (newState.position.includes('Back')) {
        pos = 'Defenders'
    } else if (newState.position.includes('Midfield')){
        pos = 'Midfield'
    } else if (newState.position.includes('Forward')) {
        pos = 'Forwards'
    } else {
        pos = newState.position;
    }

    this.state.p[pos].push(newState)
}

基本上,我想将一些数组推入多个状态 属性。 不知何故,我需要将此代码 "this.state.p[pos].push(newState)" 更改为使用 this.setState。我已经 google 它并找到了类似

的东西
    this.setState({
        p : this.state.p[pos].concat([newState])
    });

显然,它根本没有帮助。你能告诉我这个吗? 非常感谢,

干杯!!

如果您确实需要深度嵌套状态,则需要用新对象替换整个 p 属性。例如使用 Object.assign

this.setState({
  p: Object.assign(this.state.p, {
    [pos]: this.state.p[pos].concat(newState)
  })
})

Danny Kim,您在要添加的新密钥上缺少引号。将最后一行更改为

this.state.p['pos'].push(newState)