下一个js页面转换时的加载屏幕 [英] Loading Screen on next js page transition
问题描述
当我在Nextjs应用程序中更改路线时,例如/home->/about,我正在尝试实现加载屏幕.
I am trying to implement a loading screen when changing routes in my Nextjs app ,for example /home -> /about.
我当前的实现如下.我将初始加载状态设置为false,然后在 componentDidMount 上进行更改.我还调用了 componentDidMount 中的 Router.events.on 函数,以在路线更改开始时更改加载状态.
My current implementation is as follows. I am setting the initial loaded state to false and then changing it on componentDidMount. I am also calling the Router.events.on function inside componentDidMount to change the loading state when the route change starts.
_em._app.js 在页面文件夹中
_app.js in pages folder
class MyApp extends App {
constructor(props) {
super(props);
this.state = {
loaded: false,
};
}
componentDidMount() {
this.setState({ loaded: true });
Router.events.on('routeChangeStart', () => this.setState({ loaded: false }));
Router.events.on('routeChangeComplete', () => this.setState({ loaded: true }));
}
render() {
const { Component, pageProps } = this.props;
const { loaded } = this.state;
const visibleStyle = {
display: '',
transition: 'display 3s',
};
const inVisibleStyle = {
display: 'none',
transition: 'display 3s',
};
return (
<Container>
<>
<span style={loaded ? inVisibleStyle : visibleStyle}>
<Loader />
</span>
<span style={loaded ? visibleStyle : inVisibleStyle}>
<Component {...pageProps} />
</span>
</>
</Container>
);
}
}
这很好用,但我觉得可能有更好的解决方案,更优雅的解决方案.这是实现此加载功能的唯一麻烦方法,还是有替代方法?
This works perfectly fine but I feel like there may be a better solution more elegant solution. Is this the only way which isn't cumbersome to implement this loading feature or is there an alternative ?
推荐答案
为什么不按_app.js
import React from 'react';
import Router from 'next/router';
import App, { Container } from 'next/app';
import NProgress from 'nprogress';
NProgress.configure({ showSpinner: publicRuntimeConfig.NProgressShowSpinner });
Router.onRouteChangeStart = () => {
// console.log('onRouteChnageStart triggered');
NProgress.start();
};
Router.onRouteChangeComplete = () => {
// console.log('onRouteChnageComplete triggered');
NProgress.done();
};
Router.onRouteChangeError = () => {
// console.log('onRouteChnageError triggered');
NProgress.done();
};
export default class MyApp extends App { ... }
链接到 nprogress .
您还需要包括样式文件.如果将css文件放在static
目录中,则可以按以下方式访问样式:
You also need to include style file as well. If you put the css file in static
directory, then you can access to the style as follow:
<link rel="stylesheet" type="text/css" href="/static/css/nprogress.css" />
确保CSS在所有页面中都可用...
Make sure the CSS is available in all pages...
它将适用于所有更改的路线.
It will work for all you routes changing.
这篇关于下一个js页面转换时的加载屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!