【问题标题】:React Hook useEffect has a missing dependency Either include it or remove the dependency array react-hooks/exhaustive-depsReact Hook useEffect 缺少依赖要么包含它要么删除依赖数组 react-hooks/exhaustive-deps
【发布时间】:2020-06-18 12:05:59
【问题描述】:

我的反应应用程序给了我这个警告:

React Hook useEffect 缺少依赖项 要么包含它,要么 移除依赖数组 react-hooks/exhaustive-deps

如果我将 Stateful 组件移动到 useEffect 挂钩内部,那么我的 Button 将无法再访问 setButton。有没有办法解决这个问题?

  const [value, setValue] = useState([])
  const [isLoading, setLoading] = useState(false)
  const [buttonValue, setButton] = useState(false)

这是我的 useEffect Hook

  useEffect(() => {
    axios.get('http://localhost:5000/').then(res => setValue(res.data))

    if (buttonValue === 'delete') {
      setLoading(true)
      axios.delete('http://localhost:5000/delete').then(() => {
        setLoading(false)
        setButton(null)
      })
    } else if (buttonValue === 'create') {
      setLoading(true)
      axios.post('http://localhost:5000/').then(() => {
        setLoading(false)
        setButton(null)
      })
    }
  }, [isLoading])

这些是我的按钮

   <Form>
     <Form.Group>
       <Button variant='success' className='button' onClick={() => setButton('create')} id='create'>Create Sales Order</Button>
     </Form.Group>
     <Form.Group>
       <Button variant='danger' className='button' onClick={() => setButton('delete')} id='delete'>Delete Sales Order</Button>
     </Form.Group>
   </Form>

【问题讨论】:

  • 它只是想让你将buttonValue 添加到依赖数组中。使用当前设置,效果只会在挂载时运行,并且当isLoading 更改时。但是由于您在挂钩中使用buttonValue,因此警告您应该将其作为依赖项包含在内。

标签: reactjs


【解决方案1】:

useEffect 将在依赖数组中的任何项目发生更改时重新运行效果回调(例如,加载从 false 变为 true)。

您收到的警告是因为您在效果回调中使用了 buttonValue,但未包含在依赖项数组中。因此,当您在按钮的单击处理程序中调用 setButton() 时,什么都不会发生,因为 useEffect 不会检测到任何更改以重新运行效果回调。

但是,我建议你更改实现,useEffect 应该用于Side Effects(例如,当用户选择下拉菜单时触发列表更新),而不是效果本身(点击提交按钮)。

我会这样重写代码:

  const [value, setValue] = useState([]);
  const [isLoading, setLoading] = useState(false);

  useEffect(() => {
    axios.get('http://localhost:5000/').then(res => setValue(res.data))
  }, [])


  const handleCreateClick = () => {
      setLoading(true);
      axios.post('http://localhost:5000/create').then(() => {
        setLoading(false);
      });
  }

  const handleDeleteClick = () => {
      setLoading(true);
      axios.delete('http://localhost:5000/delete').then(() => {
        setLoading(false);
      });
  }


  return (
        <Form>
          <Form.Group>
             <Button variant='success' className='button' onClick={handleCreateClick} id='create'>Create Sales Order</Button>
          </Form.Group>
          <Form.Group>
             <Button variant='danger' className='button' onClick={handleDeleteClick} id='delete'>Delete Sales Order</Button>
          </Form.Group>
        </Form>
  );

由于我们将效果与副作用分开,因此上述方法更具可读性且不易出错。

【讨论】:

    猜你喜欢
    • 2021-10-21
    • 1970-01-01
    • 2020-06-09
    • 2021-10-31
    • 2021-07-15
    • 2021-12-06
    • 1970-01-01
    • 2023-01-15
    • 2022-01-09
    相关资源
    最近更新 更多