了解 react-hooks/exhaustive-deps useEffect 和调度事件

understanding react-hooks/exhaustive-deps useEffect and dispatching events

我有这个警告:

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

使用此代码:

import { useDispatch } from 'react-redux';
import openSocket from "socket.io-client";
import {populateCustomers} from './slices/CustomerSlice';
const ENDPOINT = config.ENDPOINT; //socket address

function App() {
  const dispatch = useDispatch();
  useEffect(() => {
    const socket = openSocket(ENDPOINT);
    //hydrate
    socket.on("hydrateCustomers",data=>dispatch(populateCustomers(data)))

  },[]);

想法是打开一次套接字,然后在服务器事件上 - 数据从响应分派到 redux 存储中。

我很确定我想要一个空的依赖项数组,因为我只希望它 运行 一次...有没有更好的方法来处理这种情况?或者我应该忽略这个警告?

useDispatch 引用是 stable,因此您可以毫无问题地将它添加到依赖项数组,它仍然只会 运行 挂载:

The dispatch function reference will be stable as long as the same store instance is being passed to the . Normally, that store instance never changes in an application.

However, the React hooks lint rules do not know that dispatch should be stable, and will warn that the dispatch variable should be added to dependency arrays for useEffect and useCallback. The simplest solution is to do just that:

export const Todos() = () => {
 const dispatch = useDispatch();

 useEffect(() => {
   dispatch(fetchTodos())
   // Safe to add dispatch to the dependencies array
 }, [dispatch])
}

因此您可以安全地将 },[]); 更改为 },[dispatch]);