我强迫下面的代码运行catch
块,其中将getFoodCategoriesFailed
设置为true
,然后在进入finally
块时仍显示{{ 1}}为getFoodCategoriesFailed
,这是它的初始值。有人可以指出我做错了什么,并帮助我解决它。
false
答案 0 :(得分:0)
useState不会同步更改
如果要同步使用useState,请使用下面的代码
import { useState, useRef, useEffect } from 'react';
export default function useStateCallback(initialState) {
const [state, setState] = useState(initialState);
const cbRef = useRef(null); // mutable ref to store current callback
// eslint-disable-next-line no-shadow
const setStateCallback = (state, cb) => {
cbRef.current = cb; // store passed callback to ref
setState(state);
};
useEffect(() => {
// cb.current is `null` on initial render, so we only execute cb on state *updates*
if (cbRef.current) {
cbRef.current(state);
cbRef.current = null; // reset callback after execution
}
}, [state]);
return [state, setStateCallback];
}
答案 1 :(得分:0)
我不是专家,如果不能解决问题,请您道歉,但是...我可以尝试以下几种方法:
考虑将onFoodCategories检索到(或作为一个新的)useEffect调用(并将getFoodCategoriesFailed添加到依赖项列表)是否有意义。
类似的东西
const getCategories = async (url) => {
const { request } = await requestor.get({ url });
let localFoodCategories = undefined;
let localGetFoodCategoriesFailed = true;
request.then((response) => {
localFoodCategories = response;
localGetFoodCategoriesFailed = false;
}).catch(() => {
}).finally(() => {
setFoodCategories(localFoodCategories);
setGetFoodCategoriesFailed(localGetFoodCategoriesFailed);
onFoodCategoriesRetrieved(localGetFoodCategoriesFailed, localFoodCategories?.food_categories);
});
};