在React中创建加载超时页面



当从后端加载某些数据花费太长时间时,我试图制作一个超时页面,但我在一些非常容易的事情上失败了(我认为(,我的代码目前是

const Layout = ({ lang: { language, loadingLang }, getLang }) => {
const time = useRef(0);
const timer = useRef(false);
useEffect(() => {
// Get the language
if (!language && !loadingLang) {
getLang();
//Start the timer
timer.current = setInterval(function() {
++time.current;
console.log(time.current);
}, 1000);
return () => {
clearInterval(timer.current);
};
}
// Prevent any useless errors with net line:
// eslint-disable-next-line
}, []);
if (language && !loadingLang) {
// stop the timer if whe have the data
clearInterval(timer.current);
}
if (!language && time.current > 10) {
return <LoadingTimeoutPage />;
}
// If the language data does not exist or is loading show the preloader
if (!language && time.current < 10) {
return <Preloader />;
}
return (
<Router>
<NavBar />
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/hire" component={Hire} />
<Route exact path="/swimschool" component={SwimSchool} />
<Route exact path="/login" component={Login} />
<PrivateRoute path="/dashboard" component={DashBoard} roles={['any']} />
<Route exact path="*" component={PDNE} />
</Switch>
</Router>
);
};

我想这应该很简单,但我就是无法让它按照预期的方式工作,现在它只会显示预加载程序,即使在10秒钟后,我是不是做错了什么,只是忽略了?

您需要定期检查计时器值,并在超过限制时触发重新渲染:

const Layout = ({/* ... */}) => {
const [limitExceeded, setLimitExceeded] = useState(false);
const time = useRef(0);
const timer = useRef(false);
useEffect(() => {
if (!language && !loadingLang) {
getLang();
timer.current = setInterval(function() {
if(time.current > 10) {
// trigger a re-render by setting limitExceeded to true
setLimitExceeded(true);
clearInterval(timer.current);
} else {
++time.current;
}
}, 1000);
return () => clearInterval(timer.current);
}
}, []);
useEffect(() => {
if (language && !loadingLang) clearInterval(timer.current);
}, [language, loadingLang]);
// ...
if (!language && limitExceeded) {
return <LoadingTimeoutPage />;
}
// ...
}

最新更新