了解 react-hooks/exhaustive-deps useEffect 和调度事件 [英] understanding react-hooks/exhaustive-deps useEffect and dispatching events

查看:92
本文介绍了了解 react-hooks/exhaustive-deps useEffect 和调度事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个警告:

React Hook useEffect 缺少依赖项:'dispatch'.包括它或删除依赖数组 react-hooks/exhaustive-deps

使用此代码:

import { useDispatch } from 'react-redux';从socket.io-client"导入 openSocket;从'./slices/CustomerSlice'导入{populateCustomers};常量端点 = config.ENDPOINT;//套接字地址功能应用(){const dispatch = useDispatch();useEffect(() => {const socket = openSocket(ENDPOINT);//水合物socket.on("hydraCustomers",data=>dispatch(populateCustomers(data)))},[]);

这个想法是一个套接字被打开一次,并且在服务器事件上 - 数据从响应分派到 redux 存储中.

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

解决方案

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

<块引用>

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

<块引用>

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

<块引用>

export const Todos() = () =>{const dispatch = useDispatch();useEffect(() => {调度(fetchTodos())//安全地将调度添加到依赖项数组}, [派遣])}

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

I have this warning:

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

with this code:

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)))

  },[]);

the idea is that a socket is opened once, and on server events - data is dispatched from the response into the redux store.

I'm pretty sure I want an empty dependency array, as I only want this to run once... Is there a better way to handle this situation? or should I ignore this warning?

解决方案

The useDispatch reference is stable, so you can add it to the dependency array without issue, it'll still only run on mount:

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])
}

So you can safely change },[]); to },[dispatch]);

这篇关于了解 react-hooks/exhaustive-deps useEffect 和调度事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆