reactjs - 用大数组反应 useState() 钩子
问题描述
使用 React 钩子,如果我们需要更新一个大型状态数组的一个元素,直接修改状态然后用它调用 set 是一种反模式吗?或者是否有必要先复制一个巨大的数组以传递给 set()?我想避免在每次状态更改时复制一个大数组。下面的代码不好吗?
const [bigArray, setBigArray] = useState(Array(SOME_HUGE_NUMBER).fill(false));
bigArray[15] = true;
setBigArray(bigArray);
解决方案
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.
推荐阅读
- c - 嵌套二维结构数组的大小
- python - Django 部署服务器上的文件编码
- google-chrome - 我正在编写一个网站,但粗体和斜体不起作用
- php - 致命错误:调用字符串上的成员函数 prepare()
- c - 我仍然可以对一个有第二个 malloc() 调用的变量调用 free() 吗?
- json - “对象”类型上不存在属性“位置”
- php - 无法使用 PHP 7.2 从 MySQL 数据库中选择数据
- r - 正则表达式 - 匹配两个两位数之间所有值的最佳方法?
- sql - 如何根据另一列计算行数?
- django - 没有对象的 Django ManyToMany 相关管理器返回 True