我需要将项目连接到存储在 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'));