gpt4 book ai didi

reactjs - 如何使用 React Native 中的索引更新 useState 中的数组

转载 作者:行者123 更新时间:2023-12-05 00:46:18 25 4
gpt4 key购买 nike

使用 useState Hook 更新数组时遇到问题。我想要的是我有一个填充了 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 检查数组的引用,如果更改则重新渲染,否则不进行。

关于reactjs - 如何使用 React Native 中的索引更新 useState 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61302689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com