简体   繁体   English

自定义挂钩 State 更改未更新所有组件

[英]Custom Hook State Change Not Updating All Components

I have a custom hook defined as follows:我有一个自定义钩子定义如下:

export const useData = (): [boolean, () => Promise<void>] => {

    const [isLoading, setIsLoading] = useState(false);

    const fetch = async () => {
        setIsLoading(true);
        await new Promise<void>(resolve => setTimeout(resolve, 2500)); // mock a network request timeout
        setIsLoading(false);
    };

    return [isLoading, fetch];
};

I have two components, A and B that then use the hook as follows:我有两个组件, AB ,然后按如下方式使用钩子:

const [ isLoading, fetch ] = useData();

My problem is when component A calls fetch , isLoading reflects the proper value in component A but not in Component B .我的问题是,当组件A调用fetch时, isLoading反映了组件A中的正确值,而不是组件B中的值。 In other words, isLoading is never updated in B when fetch is called by A .换句话说,当fetchA调用时, isLoading永远不会在B中更新。 Am I missing something here?我在这里错过了什么吗?

Any advice would be appreciated.任何意见,将不胜感激。 Thanks.谢谢。

My problem is when component A calls fetch, isLoading reflects the proper value in component A but not in Component B. In other words, isLoading is never updated in B when fetch is called by A. Am I missing something here?我的问题是,当组件 A 调用 fetch 时,isLoading 反映了组件 A 中的正确值,而不是组件 B 中的值。换句话说,当 A 调用 fetch 时,isLoading 永远不会在 B 中更新。我在这里遗漏了什么吗?

Yes, hooks are not meant to be used like that.是的,钩子不应该那样使用。 From docs:来自文档:

Do two components using the same Hook share state?使用同一个 Hook 的两个组件是否共享 state? No. Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated.不可以。自定义 Hook 是一种重用有状态逻辑的机制(例如设置订阅和记住当前值),但是每次使用自定义 Hook 时,所有 state 和其中的效果都是完全隔离的。

I think you must somehow combine your hook with Context API to achieve your goal.我认为您必须以某种方式将您的钩子与Context API 结合起来以实现您的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM