首页 > 解决方案 > 用大数组反应 useState() 钩子

问题描述

使用 React 钩子,如果我们需要更新一个大型状态数组的一个元素,直接修改状态然后用它调用 set 是一种反模式吗?或者是否有必要先复制一个巨大的数组以传递给 set()?我想避免在每次状态更改时复制一个大数组。下面的代码不好吗?

const [bigArray, setBigArray] = useState(Array(SOME_HUGE_NUMBER).fill(false));

bigArray[15] = true;
setBigArray(bigArray);

标签: reactjsreact-hooksuse-state

解决方案


You should not modify state directly, it may lead to bugs. So best practice is to clone the array and then modify that value.

If you don't use that variable it will be automatically garbage collected, so it should not impact performance. Consider following example:

const bigArrayTmp = [... bigArray] ; 
bigArrayTmp[15] = true; 
setBigArray(bigArrayTmp); 

After this code if bigArrayTmp is not being used it will be garbage collected. So won't take your memory.


推荐阅读