在嵌套钩子中:如何知道它是否已经在当前组件(实例)中被调用并访问任何以前计算/保存的值?
最好不要让Component
位作者/钩子用户知道这一点,也不需要做任何特殊的事情.
实例
举例说明这个问题:
const useNestedHook = () => {
// Some heavy work with the same result for each component instance.
// Is it possible to remember the result of this work when
// this hook is used again in the same component instance?
// So I would like to save a state which all uses of useNestedHook
// could access as long as they are in the same component instance.
}
const useHookA = () => {
useNestedHook();
};
const useHookB = () => {
useNestedHook();
};
const Component = () => {
useHookA();
// Would like to avoid useNestedHook repeating its work since it's
// used in the same component and would have this same result (per definition)
// Preferably without the Component author having to know anything about this.
useHookB();
};
想象的解决方案
类似于"命名"共享状态的东西,它将允许访问相同的共享状态(在相同的组件实例中),无论它在哪个钩子中使用.与往常一样,每个组件实例都有自己的独立状态.也许是这样的:
const [state, setState] = useSharedState("stateId", initialValue);