从 useEffect 访问上下文
Accessing context from useEffect
我有一个上下文,用于在我的应用程序执行长 运行 任务时显示整页微调器。
当我尝试在 useEffect
中访问它时,我收到 react-hooks/exhaustive-deps
ESLint 消息。例如下面的代码,虽然它按预期工作,但声明 busyIndicator
是一个缺失的依赖项:
const busyIndicator = useContext(GlobalBusyIndicatorContext);
useEffect(() => {
busyIndicator.show('Please wait...');
}, []);
This 文章建议我可以用 useCallback
包装函数,它可能如下所示:
const busyIndicator = useContext(GlobalBusyIndicatorContext);
const showBusyIndicator = useCallback(() => busyIndicator.show('Please wait...'), []);
useEffect(() => {
showBusyIndicator();
}, [showBusyIndicator]);
虽然这可行,但它已将问题移至 useCallback
行,该行现在抱怨缺少依赖项。
在这种情况下可以忽略 ESLint 消息吗?还是我错过了什么?
如果你的 busyIndicator
在组件的生命周期内没有改变,你可以简单地将它作为依赖添加到 useEffect
:
const busyIndicator = useContext(GlobalBusyIndicatorContext);
useEffect(() => {
busyIndicator.show('Please wait...');
}, [busyIndicator]);
如果 busyIndicator
可以更改并且您不想看到错误,那么您可以使用 useRef
挂钩:
const busyIndicator = useRef(useContext(GlobalBusyIndicatorContext));
useEffect(() => {
busyIndicator.current.show('Please wait...');
}, []);
The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class. read more
无需将 useContext 包装在 useRef Hook 中。
您可以更新上下文数据,只需调用 useEffect Brackets
像这样。
const comingData = useContext(taskData);
useEffect(() => {
console.log("Hi useEffect");
}},[comingData]); //context data is updating here before render the component
我有一个上下文,用于在我的应用程序执行长 运行 任务时显示整页微调器。
当我尝试在 useEffect
中访问它时,我收到 react-hooks/exhaustive-deps
ESLint 消息。例如下面的代码,虽然它按预期工作,但声明 busyIndicator
是一个缺失的依赖项:
const busyIndicator = useContext(GlobalBusyIndicatorContext);
useEffect(() => {
busyIndicator.show('Please wait...');
}, []);
This 文章建议我可以用 useCallback
包装函数,它可能如下所示:
const busyIndicator = useContext(GlobalBusyIndicatorContext);
const showBusyIndicator = useCallback(() => busyIndicator.show('Please wait...'), []);
useEffect(() => {
showBusyIndicator();
}, [showBusyIndicator]);
虽然这可行,但它已将问题移至 useCallback
行,该行现在抱怨缺少依赖项。
在这种情况下可以忽略 ESLint 消息吗?还是我错过了什么?
如果你的 busyIndicator
在组件的生命周期内没有改变,你可以简单地将它作为依赖添加到 useEffect
:
const busyIndicator = useContext(GlobalBusyIndicatorContext);
useEffect(() => {
busyIndicator.show('Please wait...');
}, [busyIndicator]);
如果 busyIndicator
可以更改并且您不想看到错误,那么您可以使用 useRef
挂钩:
const busyIndicator = useRef(useContext(GlobalBusyIndicatorContext));
useEffect(() => {
busyIndicator.current.show('Please wait...');
}, []);
The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class. read more
无需将 useContext 包装在 useRef Hook 中。 您可以更新上下文数据,只需调用 useEffect Brackets 像这样。
const comingData = useContext(taskData);
useEffect(() => {
console.log("Hi useEffect");
}},[comingData]); //context data is updating here before render the component