Updating React state as a 2d array?

送分小仙女□ 提交于 2021-01-29 05:39:44

问题


Given this 2d array React state,

this.state =
  board: [
    [null, null, null, null],
    [null, {id: 21, canSelect: false}, null, null],
    [null, {id: 42, canSelect: false}, null, null],
    [null, null, null, null]
  ]
}

I have 3 main questions regarding using setState to update this state:

1) How would I target a specific index within this 2d array state in React? Something like board[1][1]: {newObject}?

2) How would I update only the "canSelect" values for each?

3) If there were an unknown number of array indexes I would need to update (say between 2 and 8), how would I update only those indexes?

Any help is really appreciated :)


回答1:


1) How would I target a specific index within this 2d array state in React?

To access let's say, the object with id = 21 do that:

console.log(this.state.board[1][1].id)

2) How would I update only the "canSelect" values for each?

To change a specific canSelect property do it in a immutable way:

onChange = e => this.setState(state =>({
    ...state,
    board : state.board.map((arr, i) => arr.map((item,j) =>{
        if(!item.hasOwnProperty('canSelect') return item
        return {...item, canSelect: !state.board[i][j]}
    }))
}))

If there were an unknown number of array indexes I would need to update (say between 2 and 8), how would I update only those indexes?

If you want non-consecutive arrays(sparse), just create an Object and then map it's keys instead of indexes:

const obj = {myKey : 'foo'}
console.log(obj.myKey) //foo

See more about sparse arrays in this question, but the gist here is do not use it, even if they do not take up more space than a "normal" array, what you really want is a hashing mecanism that map key names to values, good old JSON

Update

Based on your comments I've realized that I misunderstood the third problem, but I'm not excluding it cause it can be useful.

So let's assume you want to update the canSelect property on every id contained in a list:

const idsToUpdate = [1,22]

But you don't know if the given ids exist on your current collection, the solution would be iterate through every item, check if they aren't null, then check if the id is inside the idsToUpdate list and only then update the canSelect property:

this.setState(state =>({
    ...state,
    board : state.board.map((arr,i) => arr.map((item, j) =>{
        if(!item) return item
        if(!idsToUpdate.includes(item.id)) return item
        return {...item, canSelect: true}
    }))
}))


来源:https://stackoverflow.com/questions/57147297/updating-react-state-as-a-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!