gpt4 book ai didi

arrays - 使用 useState Hook 将项目添加到存储在 React 状态的数组中的正确方法?

转载 作者:行者123 更新时间:2023-12-01 21:41:42 25 4
gpt4 key购买 nike

我需要将项目连接到存储在 React 组件状态中的数组。我有一个关于 stackblitz 的例子,我无法理解为什么数组没有增长,因为我使用扩展运算符添加元素以连接到现有数组。任何帮助表示赞赏

链接:https://stackblitz.com/edit/react-usestate-example-ebzt6g?file=index.js

import React from 'react';
import { useState, useEffect } from 'react';
import { render } from 'react-dom';
import './style.css';

const App = () => {

const [name, setName] = useState('React');
const [coords, setCoords] = useState([]);

const success = (position) => {
// setCoords(coords.concat(position.coords))
setCoords([
...coords,
position.coords
])
console.log("success! position=", position);
}

useEffect(() => {
console.log("useEffect -> coords =", coords);
});

useEffect(() => {
setInterval(() => {
success({coords : {latitude: Math.random()*51, longitude: Math.random()*2.6}});
}, 5000);
}, []);

return (
<p>example to demonstrate growing an array stored with React usestate hook</p>
)
}

render(<App />, document.getElementById('root'));


最佳答案

useEffect(() => {
setInterval(() => {
success({coords : {latitude: Math.random()*51, longitude: Math.random()*2.6}});
}, 5000);
}, []);

作为第二个参数的空数组告诉 React 只创建一次这个效果,并且永远不会更新它。创建时,它在其闭包中引用了成功函数,而该成功函数又引用了 coords。由于这全部来自第一次渲染,coords 是一个空数组。

因此,每次您调用 success 时,您都会将新坐标添加到该空数组并调用 setCoords。该数组永远不会增长,因为您的起点始终是空数组。而且您永远不会看到新阵列,因为它们只存在于以后的渲染中。

解决这个问题的最简单方法是使用 setCoords 的函数版本。 React 会调用该函数并传入最新的坐标值

const success = (position) => {
setCoords(prevCoords => {
return [
...prevCoords,
position.coords
]
})
}

关于arrays - 使用 useState Hook 将项目添加到存储在 React 状态的数组中的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61273907/

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