Eslint 错误 React Hook useEffect 缺少依赖项:“navigate”

问题描述 投票:0回答:1

为什么我会收到此 eslint 错误?

React Hook useEffect has a missing dependency: 'navigate'. Either include it or remove the dependency array.

我不想将导航放在那里,因为在每个导航函数上都会调用它。我只想在身份验证状态更改时调用它,因此我在依赖项中添加了身份验证变量,但 eslint 说我也必须在依赖项中使用导航功能,但为什么呢?我该如何解决这个错误?

代码:

import { Route, Routes, useNavigate } from "react-router-dom"
import Login from "./pages/login"
import PasswordResetConfirm from "./components/PasswordResetConfirm/PasswordResetConfirm"
import useAuth from "./hooks/useAuth"
import { Index } from "./pages";
import { useEffect } from "react";
import Holidays from "./pages/holidays";

function App() {
  const navigate = useNavigate();
  const { auth } = useAuth();

  useEffect(() => {
    if(!auth) {
      console.log(auth);
      navigate('/login');
    }
  }, [auth]);
  return (
    <Routes>
      { !auth ? 
        <>
          <Route path="/reset_password" element={<PasswordResetConfirm />} />
          <Route path="/login" element={<Login />} />
        </>
        :
        <>
          <Route path="/" element={<Index />} />
          <Route path="/holidays" element={<Holidays />} />
        </>
      } 
    </Routes>
  )
}

export default App

reactjs eslint
1个回答
0
投票

一种简单的方法是,忽略以其他方式显示的行的规则是使用

useCallback

创建自定义包装器
import { useCallback } from 'react'
import { useNavigate } from 'react-router-dom'

/**
 * Wraps the `navigate` function provided by `useNavigate` from
 * react router in a `useCallback` function to avoid redefinition every render
 */
export const useCustomNavigation = () => {
  const navigate = useNavigate()
  return useCallback(navigate, [navigate])
}

现在您应该避免在每个渲染中重新定义

navigate
,这样您的
useEffect
就不应该重新运行每个渲染。

用途:

const navigate = useCustomNavigation()
// Your useEffect logic and other component logic here

© www.soinside.com 2019 - 2024. All rights reserved.