使用 useState 钩子将项目添加到以 React 状态存储的数组的正确方法?

Lau*_*ass 1 arrays reactjs use-state

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


Run Code Online (Sandbox Code Playgroud)

Nic*_*wer 5

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

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

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

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

const success = (position) => {
  setCoords(prevCoords => {
    return [
      ...prevCoords,
      position.coords
    ]
  })
}
Run Code Online (Sandbox Code Playgroud)