我正在尝试实现这一点:
useEffect(() => {
setSingleFieldData({ ...singleFieldData, id: uuidv4() });
}, []);
基本上,当组件加载时,我想使用uuidv4将id添加到singleFieldData中,我使用的是诸如“ componentDidMount”之类的useEffect并使用空括号,但是我得到此警告:
/src/components/FormBuilderPage/utils/FieldGenerator.js
Line 64:6: React Hook useEffect has a missing dependency: 'singleFieldData'. Either include it or remove the dependency array. You can also do a functional update 'setSingleFieldData(s => ...)' if you only need 'singleFieldData' in the 'setSingleFieldData' call react-hooks/exhaustive-deps
将singleFieldData添加到依赖项不起作用,因为我只希望它在渲染时运行一次,该怎么做才能消除该警告
答案 0 :(得分:3)
当要引用prevState
时,React useState
提供了您必须使用的回调函数版本:
useEffect(() => {
setSingleFieldData(prevSingleFieldData => ({
...prevSingleFieldData, id: uuidv4()
}));
}, []);
在某些情况下,您可以设置初始状态本身。