带钩的useEffect给我警告消息

时间:2020-02-29 13:15:14

标签: reactjs react-hooks use-effect

我正在尝试实现这一点:

 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添加到依赖项不起作用,因为我只希望它在渲染时运行一次,该怎么做才能消除该警告

1 个答案:

答案 0 :(得分:3)

当要引用prevState时,React useState提供了您必须使用的回调函数版本:

useEffect(() => {
    setSingleFieldData(prevSingleFieldData => ({
        ...prevSingleFieldData, id: uuidv4() 
    }));
}, []);

Docs - Functional updates

在某些情况下,您可以设置初始状态本身。