问题描述
我有一个上下文,用于在我的应用程序执行长时间运行的任务时显示整页微调器.
当我尝试在 useEffect
中访问它时,我收到了一个 react-hooks/exhaustive-deps
ESLint 消息.例如,下面的代码虽然按预期工作,但声明 busyIndicator
是一个缺失的依赖项:
const busyIndicator = useContext(GlobalBusyIndicatorContext);useEffect(() => {busyIndicator.show('请稍候...');}, []);
这篇 文章建议我可以用 包装函数useCallback
可能如下所示:
const busyIndicator = useContext(GlobalBusyIndicatorContext);const showBusyIndicator = useCallback(() => busyIndicator.show('请稍候...'), []);useEffect(() => {showBusyIndicator();}, [showBusyIndicator]);
尽管这可行,但它已将问题移至 useCallback
行,该行现在抱怨缺少依赖项.
在这种情况下可以忽略 ESLint 消息还是我遗漏了什么?
如果你的 busyIndicator
在组件的生命周期内没有改变,你可以简单地将它作为依赖添加到 useEffect代码>:
const busyIndicator = useContext(GlobalBusyIndicatorContext);useEffect(() => {busyIndicator.show('请稍候...');}, [busyIndicator]);
如果可以更改 busyIndicator
并且您不想看到错误,那么您可以使用 useRef
钩子:
const busyIndicator = useRef(useContext(GlobalBusyIndicatorContext));useEffect(() => {busyIndicator.current.show('请稍候...');}, []);
useRef() 钩子不仅仅用于 DOM 引用.ref"对象是一个通用容器,其当前属性是可变的并且可以保存任何值,类似于类上的实例属性.阅读更多
I have a context that is used to show a full page spinner while my application is performing long running tasks.
When I attempt to access it inside useEffect
I get a the react-hooks/exhaustive-deps
ESLint message. For example the following code, although it works as expected, states that busyIndicator
is a missing dependency:
const busyIndicator = useContext(GlobalBusyIndicatorContext);
useEffect(() => {
busyIndicator.show('Please wait...');
}, []);
This article suggests that I could wrap the function with useCallback
which might look as follows:
const busyIndicator = useContext(GlobalBusyIndicatorContext);
const showBusyIndicator = useCallback(() => busyIndicator.show('Please wait...'), []);
useEffect(() => {
showBusyIndicator();
}, [showBusyIndicator]);
Although this works it has moved the issue to the useCallback
line which now complains about the missing dependency.
Is it ok to ignore the ESLint message in this scenario or am I missing the something?
If your busyIndicator
is not changed during the life of the component, you could simply add it as a dependency to useEffect
:
const busyIndicator = useContext(GlobalBusyIndicatorContext);
useEffect(() => {
busyIndicator.show('Please wait...');
}, [busyIndicator]);
If busyIndicator
could be changed and you don't want to see an error, then you could use useRef
hook:
const busyIndicator = useRef(useContext(GlobalBusyIndicatorContext));
useEffect(() => {
busyIndicator.current.show('Please wait...');
}, []);
这篇关于从 useEffect 访问上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!