简体   繁体   中英

React Hooks useState array storage problem

I have the following problem: I have a method that returns a multidimensional array in my Grids component. 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

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.

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 .

You can solve this by doing the following:

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

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