Почему состояние загрузки true никогда не регистрируется, а регистрируется, когда функция асинхронна, в следующих кодах и в поле ниже?При вызове того же хука в функции, что происходит?
код
codesandbox
function App() {
const [loadingWithUseState, setLoadingWithUseState] = useState(false);
const [loadingWithReducer, setLoadingWithReducer] = useReducer(
(acc, next) => ({ ...acc, ...next }),
{ loadingWithReducer: false }
);
const onClickWithUseState = () => {
setLoadingWithUseState(true);
setLoadingWithUseState(false);
};
const onClickWithReducer = () => {
setLoadingWithReducer({ loadingWithReducer: true });
setLoadingWithReducer({ loadingWithReducer: false });
};
const onClickWithUseStateAsync = async () => {
setLoadingWithUseState(true);
await delay();
setLoadingWithUseState(false);
};
const onClickWithReducerAsync = async () => {
setLoadingWithReducer({ loadingWithReducer: true });
await delay();
setLoadingWithReducer({ loadingWithReducer: false });
};
useEffect(() => {
console.log("loadingWithUseState changed to", loadingWithUseState);
}, [loadingWithUseState]);
useEffect(() => {
console.log("loadingWithReducer changed to", loadingWithReducer);
}, [loadingWithReducer]);
console.log("re-render", { loadingWithUseState, ...loadingWithReducer });
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={onClickWithUseState}>
{" "}
trigger load with useState{" "}
</button>
<button onClick={onClickWithReducer}>
{" "}
trigger load with useReducer{" "}
</button>
<button onClick={onClickWithUseStateAsync}>
{" "}
trigger load with async useReducer{" "}
</button>
<button onClick={onClickWithReducerAsync}>
{" "}
trigger load with async useReducer{" "}
</button>
</div>
);
}
PS я хочупостроить мысленную модель того, что происходит, когда вы вызываете несколько хуков вместе