简体   繁体   中英

How can I change an array in a state in React?

I'm using a 2-dimensional array as a state.

How can I update it?

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};
},

The line below doesn't seem to work:

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

Edit: Why do I get downvoted?!

The state is kept as a map, so the way that you're editing doesn't really make sense. My recommendation is to treat the previous state as "immutable" (my example isn't actually doing that) and replace the value wholesale.

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

It's expected to not work - you are mutating data and in very strange way (i don't get what you want to do with such setState statement).

Assuming, you want to update you 2-dimensional array I would use update addon provided by React;

import update from 'react-addons-update';

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM