在反应状态下替换整个对象

时间:2017-08-03 15:17:54

标签: javascript reactjs react-native state

有没有办法用这样的状态结构更新state

this.state = {
      structure: [
        {
          selected: false,
          name: "a",
          key: "a",
        }, {
          selected: false,
          name: "b",
          key: "b"
        }, {
          selected: false,
          name: "c",
          key: "c",
        }, {
          selected: false,
          name: "d",
          key: "d"
        }
      ]
}

我想更新状态。我是这样做的:

 _onPress = (obj, index) => {
    const oldStateSelected = obj.selected;
    const newStateObject = Object.assign({}, obj);
    newStateObject.selected = !oldStateSelected;

    const oldState = _.cloneDeep([...this.state.structure]);
    oldState.splice(index, 1);
    const newState = oldState.push(newStateObject)

    this.setState({
      structure: [newState]
    });

  }

但是,这会让我返回一个新状态

{ structure: [4] }

我认为问题是,我正在修改状态而不是替换它?! 从console.log(oldState)删除元素后{I} array,我看到它显示为oldState (3) [Object, Object, Object]。 但是当我打开它时,有4个数组元素。我想用splice删除的元素仍在那里。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

Array.prototype.push未返回数组。只需push并执行

this.setState({
  structure: oldState
});

答案 1 :(得分:0)

问题出在这一行:

int

array.push 不会返回更新的数组,当我们使用push时它会更新原始数组,因此需要将变量oldState值赋值给状态变量结构。

使用此:

const newState = oldState.push(newStateObject); 

检查此代码段:



_onPress = (obj, index) => {
    const oldStateSelected = obj.selected;
    const newStateObject = Object.assign({}, obj);
    newStateObject.selected = !oldStateSelected;

    const oldState = _.cloneDeep([...this.state.structure]);
    oldState.splice(index, 1);
    oldState.push(newStateObject)

    this.setState({
        structure: oldState      //here
    });

}