问题描述
给出这个二维数组的反应状态,
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]
]
}
关于使用 setState
更新此状态,我有3个主要问题:
I have 3 main questions regarding using setState
to update this state:
1)我将如何在React的2d数组状态内定位特定索引?类似于 board [1] [1]:{newObject}
?
1) How would I target a specific index within this 2d array state in React? Something like board[1][1]: {newObject}
?
2)我如何只更新每个的"canSelect"值?
2) How would I update only the "canSelect" values for each?
3)如果我需要更新的数组索引数量未知(例如2到8之间),我将如何仅更新那些索引?
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)我如何在React的2d数组状态内定位特定索引?
要访问该数据,假设 id = 21
的对象执行以下操作:
To access let's say, the object with id = 21
do that:
console.log(this.state.board[1][1].id)
2)我如何只更新每个的"canSelect"值?
要更改特定的 canSelect
属性,请采用不可变的方式:
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]}
}))
}))
如果我需要更新的数组索引数量未知(例如2到8之间),我将如何仅更新那些索引?
如果要使用非连续数组(稀疏),只需创建一个Object,然后映射它的键而不是索引:
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
在此,但是这里的要点是不使用它,即使它们不占用比常规"数组更多的空间,您真正想要的是映射密钥的哈希机制名称值,旧的 JSON
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
更新
根据您的评论,我意识到我误解了第三个问题,但我没有排除它,因为它可能有用.
Based on your comments I've realized that I misunderstood the third problem, but I'm not excluding it cause it can be useful.
因此,假设您要更新列表中包含的每个ID的 canSelect
属性:
So let's assume you want to update the canSelect
property on every id contained in a list:
const idsToUpdate = [1,22]
但是您不知道给定的id是否在当前集合中,解决方案将遍历每个项目,检查它们是否不为null,然后检查id是否在 idsToUpdate 之内.code>列表,然后才更新
canSelect
属性:
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}
}))
}))
这篇关于将React状态更新为2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!