如何在另一个组件 useEffect 中设置 State?

快速查看我正在尝试做的事情:


import React, { useState, useEffect } from 'react';


const MainComponent = () => {

  const [element, setElement] = useState([]);

  const [setThings] = useSomething();

  useEffect(() => {

    setThings(element);

  }, [element]);

};


const useSomething = () => {

  const [things, setThings] = useState([]);

  // do stuff now that you've received things

  return [setThings];

};

以及另一个文件中的另一个钩子。这工作得很好,并且是在 ReactJS 中使用画布的绝佳解决方案。我有一个警告被抛出,我似乎无法通过我的研究来解决它:


  Line 150:7:  React Hook useEffect has a missing dependency: 'setThings'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

在反应文档中,它说这会导致问题,因为它正在调用具有依赖性的东西,但我不知道它们在哪里?


跃然一笑
浏览 60回答 1
1回答

守着星空守着你

尝试添加setThings到 中的依赖项数组useEffect。useEffect(() => {   setThings(element); }, [element, setThings]);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript