【问题标题】:How can I change an array in a state in React?如何在 React 中更改数组的状态?
【发布时间】:2016-04-28 13:49:14
【问题描述】:

我使用二维数组作为状态。

如何更新?

getInitialState: function() {
    var board = [];
    for (var i = 0; i < i_max; i++) {
        var innerArray = [];
        for (var j = 0; j < j_max; j++) {
            innerArray.push("empty");
        }
        board.push(innerArray);
    }
    return {board: board};
},

下面的行似乎不起作用:

this.setState({board[1][2]: "full"});

编辑:为什么我会被否决?!

【问题讨论】:

  • 您遇到的错误是什么?
  • unknown: Unexpected token 表示“[”的位置

标签: javascript arrays reactjs state


【解决方案1】:

状态保存为地图,因此您编辑的方式没有任何意义。我的建议是将先前的状态视为“不可变”(我的示例实际上并没有这样做)并替换值批发。

var changedBoards = this.state.boards
changedBoards[0][1] = "full";
this.setState({boards: changedBoards})

【讨论】:

  • 现在我明白了,谢谢。我想我必须使用.slice() 来创建克隆。
【解决方案2】:

预计它不起作用 - 你正在以非常奇怪的方式改变数据(我不明白你想用这样的 setState 语句做什么)。

假设你想更新二维数组,我会使用 React 提供的 update 插件;

import update from 'react-addons-update';

this.setState(update(this.state, {
  board: { 0: { 1: { $set: 'full' } } }
}));

【讨论】:

  • 我读过关于突变的文章,但我没有直接更改this.state.board
猜你喜欢
  • 2023-01-23
  • 2020-01-27
  • 2021-11-09
  • 1970-01-01
  • 2016-01-02
  • 2021-11-05
  • 2021-05-11
  • 1970-01-01
  • 2017-08-24
相关资源
最近更新 更多