简体   繁体   English

如何处理嵌套的useEffect?

[英]How to deal with nested useEffect?

Recently started using Hooks and, as cook as they are, they are giving me a bit of a headache.最近开始使用 Hooks,尽管它们是厨师,但它们让我有点头疼。

I have a custom useFetch() hook that deals with fetching data from the API.我有一个自定义的useFetch()钩子,用于处理从 API 获取数据。

I also have a component where I need to use useFetch a few times and the results must be passed from one to another.我还有一个组件,我需要使用useFetch几次,结果必须从一个传递到另一个。

Eg:例如:

const ComponentName = () => {
  const { responseUserInfo } = useFetch('/userinfo')
  const { responseOrders } = useFetch(`/orders?id=${responseUserInfo.id}`)
  const { isOrderRefundable } = useFetch(`/refundable?id={responseOrders.latest.id}`)

  return <div>{isOrderRefundable}</div>

}

So, how do I actually "cascade" the hooks without creating 3 intermediate wrappers?那么,我如何在不创建 3 个中间包装器的情况下实际“级联”这些钩子? Do I have to use HoC?我必须使用 HoC 吗?

Your hook could return a callback, that when called does the API call:你的钩子可以返回一个回调,当被调用时 API 调用:

  const [getUserInfo, { userInfo }] = useFetch('/userinfo');
  const [getOrders, { orders }] = useFetch(`/orders`)
  const [getOrderRefundable, { isOrderRefundable }] = useFetch(`/refundable`);

  useEffect(getUserInfo, []);
  useEffect(() => { if(userInfo) getOrders({ id: userInfo.id }); }, [userInfo]);
  useEffect(() => { if(orders) getOrderRefundable({ id: /*..*/ }); }, [orders]);

But if you always depend on the whole data being fetched, I'd just use one effect to load them all:但是,如果您总是依赖于获取的整个数据,我只会使用一种效果来加载它们:

  function useAsync(fn, deps) {
    const [state, setState] = useState({ loading: true });
    useEffect(() => { 
       setState({ loading: true });
       fn().then(result => { setState({ result }); });
    }, deps);
    return state;
 }

 // in the component
 const { loading, result: { userInfo, orders, isRefundable } } = useAsync(async function() {
   const userInfo = await fetch(/*...*/);
   const orders = await fetch(/*...*/);
   const isRefundable = await fetch(/*...*/);
   return { userInfo, orders, isRefundable };
 }, []);

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

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