如何在React Native中使用其索引在useState中更新数组

Anwer Solangi

使用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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在 React -TypeScript 中使用 useState 更新、扩展数组?

如何在React Native中使用索引更改数组中的值

在 React 中使用 UseState 更新数组中的所有对象

如何在不使用useState更改React native中位置的情况下更新数组元素的值?

如何在 React Native 的其他函数中使用 useState

react native - 如何在元组数组中使用 React Hooks?

如何在React Native中使用setState()修改多维数组?

如何在React Native中使用数组映射JSON数据

如何在React Native中更新数组状态

如何在React中使用setState更新数组元素?

如何在反应本机中使用特定索引更新数组中的值

如何在React Native中使用OpenCV

如何在 React Native 中使用容器?

如何在React Native中使用Elasticsearch?

如何在Typescript中使用React Native?

如何在React Native中使用Iframe?

如何在React Native中使用componentWillUnmount?

如何在 React Native 中使用 SVG?

如何在componentWillMount中更新状态并在React Native的render函数中使用该值?

如何在React Native中使用this.state访问数组中的对象?

在 React 中使用 useState 未在函数组件中更新状态

如何在React中更新数组的元素?

在React中使用useState更新多个数组对象值

在 React 中使用 useState 更新二维数组矩阵

在 React Native 中使用 useState

当数组为空时,在 redux react 中使用索引插入/更新数组中的对象

如何在React的嵌套数组中基于其索引删除对象?

如何在React中使用useState Hook调用父函数?

如何在React Native中使用React.forwardRef()