【发布时间】:2019-04-09 13:35:55
【问题描述】:
async 调用和我在 React 中的自定义钩子有问题。
我需要从同一个自定义钩子中调用一系列 fetch,但它不尊重等待链。
我有一些按钮可以像这样工作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;
我希望自定义挂钩按按钮async/await 函数的相同顺序调用。
非常感谢。
【问题讨论】:
-
DoFetch 不返回承诺,所以你在等待 undefined 并且这不起作用。
-
@Snapstromegon 好的...你能告诉我这样做的代码吗?
标签: javascript reactjs react-hooks