使用useState钩子将项添加到存储在REACT状态的数组中的正确方法是什么? [英] Correct way to add items to an array stored in React state with useState hook?
本文介绍了使用useState钩子将项添加到存储在REACT状态的数组中的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
链接: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);
}, []);
作为第二个参数的空数组告诉Reaction只创建一次该效果,并且永远不更新它。在创建它时,它在闭包中引用了Success函数,而该Success函数又引用了coords
。由于这全部来自第一次呈现,coords
是一个空数组。
success
时,都会将新的坐标添加到那个空数组中并调用setCoods。数组永远不会增长,因为您的起点始终是空数组。而且您永远不会看到新的数组,因为这些数组只存在于以后的渲染中。
解决这一问题的最简单方法是使用函数版本的setCoods。REACT将调用该函数并传入最新的坐标值
const success = (position) => {
setCoords(prevCoords => {
return [
...prevCoords,
position.coords
]
})
}
这篇关于使用useState钩子将项添加到存储在REACT状态的数组中的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文