Redux 调度在哪些情况下会发生变化? [英] What are the cases where Redux dispatch could change?

查看:38
本文介绍了Redux 调度在哪些情况下会发生变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 react-redux v7 中,我们现在有 useDispatch() 钩子来获取对 store dispatch 的引用.请参阅此处:https://react-redux.js.org/api/hooks#usedispatch

In react-redux v7, we now have the useDispatch() hook to get a reference to the store dispatch. See here: https://react-redux.js.org/api/hooks#usedispatch

生成的 dispatch 函数需要被列为任何 useEffectuseMemo 等钩子的依赖项.这是为什么?

The resulting dispatch function then needs to be listed as a dependency for any useEffect, useMemo, etc. hooks. Why is this?

经过一些测试,该应用程序仍然可以正常运行,没有将 dispatch 列为依赖项,所以我只能假设它没有改变.

After some testing, the app still works perfectly fine without dispatch being listed as a dependency, so I can only assume it's not changing.

dispatch 函数是否会发生变化?

Is there any case where the dispatch function could change?

推荐答案

对此有两个答案.

首先,据我所知,React 钩子规则" ESLint 规则知道如何专门处理内置钩子.例如,它知道 useState() 总是返回相同的 setter 函数实例,所以你不必将它包含在一个 useEffect() 依赖数组中(同上来自 useReducer() 调用的 dispatch 函数).

First, as far as I know, the React "rules of hooks" ESLint rule knows how to handle the built-in hooks specially. For example, it knows that useState() always returns the same setter function instance, so you don't have to include that in a useEffect() dependency array (ditto for the dispatch function from a useReducer() call).

然而,lint 规则了解自定义钩子,无论它们来自库还是您自己的.因此,由于 useDispatch() 是一个自定义钩子,因此 lint 规则必须假设这个 dispatch 的东西可能改变,并试图告诉您需要将其列为依赖项.

However, the lint rule doesn't know about custom hooks, whether they be from a library or your own. So, since useDispatch() is a custom hook, the lint rule has to assume that whatever this dispatch thing is could change, and tries to tell you that you need to list it as a dependency.

第二个答案是,可以将新的存储引用传递给 <Provider>,在这种情况下,store.dispatch 会返回一个不同的 store.dispatch代码>useDispatch() 钩子.

The second answer is that it's possible to pass a new store reference to <Provider>, in which case there's a different store.dispatch being returned from the useDispatch() hook.

因此,实际上,在 deps 数组中不包含 dispatch 的情况下,代码也能正常运行,因为您的应用几乎肯定会一直使用同一个 store 实例.但是,由于 lint 规则不知道这一点,因此您可能需要将其包含在列表中以使其安静.

So, realistically, the code will run fine without including dispatch in the deps array, because your app is almost definitely using the same store instance the entire time. But, since the lint rule doesn't know that, you will probably need to include it in the list anyway to make it be quiet.

(来源:我是 Redux 维护者,并帮助指导了我们的钩子 API 的实现 :) )

(Source: I'm a Redux maintainer, and helped guide the implementation of our hooks API :) )

这篇关于Redux 调度在哪些情况下会发生变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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