且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Redux 调度在哪些情况下会发生变化?

更新时间:2021-12-15 00:45:14

对此有两个答案.

首先,据我所知,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 :) )