简体   繁体   English

有办法错开React Hooks吗?

[英]Is there a way to stagger React Hooks?

I'm trying to avoid using conditional statements with React Hooks, but I've reached a point where I may need some advanced techniques. 我试图避免在React Hooks中使用条件语句,但是我已经达到了可能需要一些高级技巧的地步。 I have here 3 hooks that depend on each other. 我这里有3个相互依赖的钩子。 Each hook returns a tuple [bool, object] that the next hook requires to execute. 每个钩子返回一个下一个钩子需要执行的元组[bool, object]

Internally, each hook is an asynchronous operation and I don't have access to modify them. 在内部,每个挂钩都是异步操作,我无权修改它们。

const [loadingA, resultA] = useHook1(); 
const [loadingB, resultB] = useHook2(resultA.prop1); // Error!
const [loadingC, resultC] = useHook3(resultB.prop2); // Error!

if (loadingA || loadingB || loadingC) {
   return <span>loading...</span>;
}


// All results are required for this component.

return <MyComponent x={resultA.x} y={resultB.y} z={resultC.z} />; 

The above breaks because useHook2 and useHook3 require the arguments to be defined. 上面的代码是中断的,因为useHook2useHook3需要定义参数。 Unfortunately, I can't use a condition like this: 不幸的是,我不能使用这样的条件:

// this is not allowed

if (!loadingA) {
   const [loadingB, resultB] = useHook2(resultA.prop1);
}

Does anyone have any tips on how to stagger hooks such that they execute based on the result of a previous asynchronous hook? 是否有人对如何交错挂钩有任何提示,以便它们可以根据先前的异步挂钩的结果执行?

Return some default value in hook2 and hook3 if the parameter is undefined . 如果参数未定义,则在hook2hook3中返回一些默认值。 If you can't modify hook2 or hook3 directly, you can always wrap them in another hook (useHook2Wrapper, useHook3Wrapper) and do the undefined value validation. 如果您不能直接修改hook2hook3 ,则始终可以将它们包装在另一个hook中(useHook2Wrapper,useHook3Wrapper)并执行未定义的值验证。

const [loadingA, resultA] = useHook1(); 
const [loadingB, resultB] = useHook2(resultA && resultA.prop1);
const [loadingC, resultC] = useHook3(resultB && resultB.prop2);
const useHook2 = (someProp) => {
  if (!someProp) {
    return [false, undefined];
  }

  // rest of the hook logic
}

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

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