简体   繁体   English

React Hooks useState 数组存储问题

[英]React Hooks useState array storage problem

I have the following problem: I have a method that returns a multidimensional array in my Grids component.我有以下问题:我有一个方法可以在我的 Grids 组件中返回一个多维数组。 I would want to store any multidimensional array recomputed in a separate list.我想将重新计算的任何多维数组存储在单独的列表中。 The problem is that when I am using my useState() declared in this way问题是当我使用以这种方式声明的useState()

const [listGrid,setListGrid] = useState<any[]>([])  

only the current state element is saved repeatedly in the array list.只有当前状态元素重复保存在数组列表中。 Follow the code of interest part :按照感兴趣的部分代码:

const [listGrid,setListGrid] = useState<any[]>([]);
const grid= initGrid(); //initialise a new grid.
 const disableButtonHandler = ():void => {
       const cloneGrid =[...grid]
      console.log(cloneGrid===grid)//are no the same!!
      setListGrid(prevListGrid=>[...prevListGrid,cloneGrid]);
};

this is the snapshot of my list with the grids saved:这是我的列表的快照,其中保存了网格:

在此处输入图片说明

so, basically, all the arrays stored in listGrid are the same and I'd want to store any change of my computed list.所以,基本上, listGrid中存储的所有数组都是相同的,我想存储我的计算列表的任何更改。

what could I do wrong with it?我能做些什么错呢? thanks in advance.提前致谢。

The matrix is represented by an array of arrays, while you are duplicating the containing array, the contained ones are still the same.矩阵由数组数组表示,当您复制包含数组时,包含的数组仍然相同。 Basically, cloneGrid[i] === grid[i] is true for 0 <= i < grid.length .基本上, cloneGrid[i] === grid[i]对于0 <= i < grid.length为真。

You can solve this by doing the following:您可以通过执行以下操作来解决此问题:

const cloneGrid = grid.map(row => [...row]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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