在React中调用自定义钩子的ASYNC

问题描述 投票:-1回答:1

我在qactxswpoi调用和我在React中的自定义钩子有问题。

我需要从同一个自定义钩子调用一系列的提取,但它不尊重await链。

我有一些像这样工作async的按钮:

onClick

这些按钮调用自定义钩子,如下所示:

(我从在线教程中获得了一些代码)

buttonDelete={() => deleteAssignedOpp(opportunity.id)}

async function deleteAssignedOpp(id) {
    await doFetch(`/opportuniy/assigned/${id}`, "DELETE");
    await doFetch("/opportuniy/assigned/list", "GET", "IN_PROGRESS");
  }

我希望按钮function useFetch() { const [url, setUrl] = useState(""); const [obj, setObj] = useState(""); const [method, setMethod] = useState("GET"); const [body, setBody] = useState(); const [state, dispatch] = useStateValue(); useEffect(() => { let didCancel = false; if (url) { const fetchData = async () => { dispatch({ type: `FETCH_${obj}_INIT` }); try { const response = await fetch( `https://myapiAddress${url}`, { method: method, //body: body, headers: new Headers({ Authorization: myFunctionForAuthorization }) } ); const result = await response.json(); if (!didCancel) { dispatch({ type: `FETCH_${obj}_SUCCESS`, payload: result }); } } catch (error) { if (!didCancel) { dispatch({ type: `FETCH_${obj}_ERROR`, payload: { error } }); } } }; fetchData(); return () => { didCancel = true; }; } }, [method, body]); const doFetch = (url, method, obj, body = "") => { setUrl(url); setObj(obj); setMethod(method); setBody(body); }; return [doFetch]; } export default useFetch; 函数的顺序调用自定义钩子。

非常感谢。

javascript reactjs react-hooks
1个回答
1
投票

您可以在useEffects钩子中尝试Promise.all。每次获取都将返回一个promise

async/await

那会有用吗

© www.soinside.com 2019 - 2024. All rights reserved.