使用 useState 挂钩附加数组未按预期工作

Appending array with useState hook not working as expected

我正在使用以下代码,并希望在使用“...”时收到多个对象的数组。

const [csv, setCsv] = useState([]);

useEffect(() => {
    d3.csv(fileName, function(fileContents) { setCsv(
        [...csv,{
            'key': fileContents['Licenseno'],
            'First Name': fileContents['First Name'],
            'Address': fileContents['Street #'] + " " + fileContents['Stname'] + " " + fileContents['Suffix'] + " " + '0' + fileContents['Zip']
        }]);
    });
},[])

相反,console.log 显示正在为每个 fileName 行重写 csv[],并且一次只包含一个对象。

为了查看这是否与 d3(我以前从未使用过)有关,我声明了一个 const arrayVar = [] 和 .appended- 这按我想要的方式工作。所以它似乎是 useState 钩子......关于如何解决这个问题有什么想法吗?

另一种使用 setState 的方法是传递一个函数。

// instead of
setCsv([...csv, { key: '...' });

// use this:
setCsv((currentState) => [ ...currentState, { key: '...' } ]);

当您将函数传递给 setState 时,当前状态将作为参数传递给该函数。这样您就不必将状态添加到 useEffect 依赖项数组。

您可以在 React Docs 中找到更多信息。