使用useState钩子将项添加到存储在REACT状态的数组中的正确方法是什么?钩子、组中、正确、状态

由网友(布丁牛奶)分享简介:我需要将项连接到存储在Reaction组件状态中的数组。我有一个关于stackblitz的例子,我不明白为什么数组没有增长,因为我使用扩散运算符将元素添加到现有数组中。感谢任何帮助链接:https://stackblitz.com/edit/react-usestate-example-ebzt6g?file=inde...我需要将项连接到存储在Reaction组件状态中的数组。我有一个关于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);
}, []);

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

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

解决这一问题的最简单方法是使用函数版本的setCoods。REACT将调用该函数并传入最新的坐标值

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

相关推荐

最新文章