使用useState挂钩更新数组时遇到麻烦。我想要的是我有一个充满n个元素的数组,其中n可以是1-10。我想使用其索引号更新元素的值。但我没有得到任何帮助。这是我要实现的代码:
import React, {useState} from 'react';
import React, {View, Text} from 'react-native';
const myScreen = props => {
const [myCustomArray, setmyCustomArray] = useState(Array.(5).fill(0));
const onClickHandler = (n) => {
// update the element in array having the index no. n
setMyCustomArray([n] = 'something');
}
但是这种方法对我没有帮助。有人有更好的办法吗?
你应该在那之前展开数组
const onClickHandler = (n) => {
const arr = [...myCustomArray];
arr[n] = 'something';
setMyCustomArray(arr);
}
react检查数组的引用,如果更改则重新渲染,否则不进行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句