我是nextjs的新手,正在使用nextjs v9.3 + next-redux-wrapper v5 + @ material-ui / core v4.2 +自定义快递服务器
我正在尝试在Nextjs应用程序中更改路线时实现加载屏幕,因此我使用framer motion在页面之间进行转换,效果很好,但现在更改路线时如何使用加载组件 >
我使用了这些方法,但是没有用: Loading Screen on next js page transition和How can I use a loading component instead of nprogress?
我当前的实现如下
_app.js
import React, { useEffect } from "react";
import { ThemeProvider } from "@material-ui/core/styles";
import { CssBaseline } from "@material-ui/core";
import { theme } from "../lib/theme";
import withRedux from "next-redux-wrapper";
import { Provider } from "react-redux";
import reduxStore from "../store/store";
import { PersistGate } from "redux-persist/integration/react";
import { AnimatePresence } from "framer-motion";
import Navbar from "../components/Navbar";
import Meta from "../components/Meta";
function MyApp(props) {
useEffect(() => {
const jssStyles = document.querySelector("#jss-server-side");
if (jssStyles && jssStyles.parentNode)
jssStyles.parentNode.removeChild(jssStyles);
}, []);
const { Component, pageProps, store, router } = props;
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<Provider store={store}>
<PersistGate persistor={store.__PERSISTOR} loading={null}>
<Meta/>
<Navbar {...props} />
<AnimatePresence exitBeforeEnter>
<Component {...pageProps} key={router.route}/>
</AnimatePresence>
</PersistGate>
</Provider>
</ThemeProvider>
);
}
export default withRedux(reduxStore)(MyApp);
答案 0 :(得分:7)
我就是这样做的。在_app.tsx
:
import { useRouter } from 'next/router';
const MyApp = ({
MainComponent,
pageProps,
}) => {
const router = useRouter();
const [pageLoading, setPageLoading] = React.useState<boolean>(false);
React.useEffect(() => {
const handleStart = () => { setPageLoading(true); };
const handleComplete = () => { setPageLoading(false); };
router.events.on('routeChangeStart', handleStart);
router.events.on('routeChangeComplete', handleComplete);
router.events.on('routeChangeError', handleComplete);
}, [router]);
return (
...
{ pageLoading
? (<div>Loading</div>)
: <MainComponent {...pageProps} />
}
...
)
}
答案 1 :(得分:-2)
这可能会有所帮助,您可以将该组件放置在布局组件中,并用其包裹_app.js
或直接将其导入_app.js
:
import React from 'react';
import Router from 'next/router';
import CustomLoadingScreen from './components/CustomLoadingScreen'; // example
Router.onRouteChangeStart = () => {
console.log('onRouteChangeStart Triggered');
<CustomLoadingScreen />;
};
Router.onRouteChangeComplete = () => {
console.log('onRouteChangeComplete Triggered');
<CustomLoadingScreen />;
};
Router.onRouteChangeError = () => {
console.log('onRouteChangeError Triggered');
<CustomLoadingScreen />;
};
您可以将<CustomLoadingScreen />
设计为在调用设备时接管设备的整个视图框。