如何设置暂停组件在显示回退之前准备就绪的时间限制? React 有内置插件来管理这个吗?
我想到的是以下事件顺序:
到目前为止,这可以通过 Suspense 和 useTransition 来完成:
const [page, setPage] = useState("/");
const [isPending, startTransition] = useTransition();
function navigate(url) {
startTransition(() => {
setPage(url);
});
}
<Button onClick={() => navigate("/otherPage")}>
Go to next page {isPending && 'Loading'}
</Button>
// Clicking this can interrupt the transition
<Button onClick={() => navigate("/")}>
Go home
</Button>
但是,在某些情况下,
/otherPage
需要很长时间才能加载,我希望它在等待 2 秒后通过 Suspense Fallback 回退到整页加载。
我该怎么做?
当我写问题时,我正在尝试不同的方法来解决问题。我找到了a解决方案,但无论如何我都会发布问题,因为其他人可能有更好的解决方案,或者有人可能会发现我的解决方案有用。
最后我写了一个hook来靠着做重担
useOptimistic
:
const useTransitionState = (initialState, timeoutMs) => {
const [internalState, setInteralState] = useState(initialState);
const [isPending, startTransition] = useTransition();
const [pendingState, setPendingState] = useOptimistic(
internalState,
(_, newState) => newState
);
useEffect(() => {
if (internalState === pendingState || !timeoutMs) return;
const timeoutId = setTimeout(() => {
setInteralState(pendingState);
}, timeoutMs);
return () => clearTimeout(timeoutId);
}, [pendingState, internalState]);
const setState = useCallback((state) => {
startTransition(() => {
setInteralState(state);
setPendingState(state);
});
});
return [internalState, setState, isPending ? pendingState : undefined];
};
视频演示: