【问题标题】:understanding react-hooks/exhaustive-deps useEffect and dispatching events了解 react-hooks/exhaustive-deps useEffect 和调度事件
【发布时间】:2021-06-10 17:17:10
【问题描述】:

我有这个警告:

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 存储。

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

【问题讨论】:

    标签: reactjs redux socket.io react-redux use-effect


    【解决方案1】:

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

    只要将相同的 store 实例传递给 .通常,该存储实例在应用程序中永远不会更改。

    然而,React hooks lint 规则并不知道 dispatch 应该是稳定的,并且会警告 dispatch 变量应该被添加到 useEffect 和 useCallback 的依赖数组中。最简单的解决方案就是这样做:

    export const Todos() = () => {
     const dispatch = useDispatch();
    
     useEffect(() => {
       dispatch(fetchTodos())
       // Safe to add dispatch to the dependencies array
     }, [dispatch])
    }
    

    所以你可以安全地将},[]); 更改为},[dispatch]);

    【讨论】:

      猜你喜欢
      • 2020-06-08
      • 2020-03-11
      • 1970-01-01
      • 2020-05-01
      • 2020-06-22
      • 1970-01-01
      • 2021-04-15
      相关资源
      最近更新 更多