问题描述
我在 pages/中使用 getServerSidePropspost/index.js:
import React from "react";
import Layout from "../../components/Layout";
function Post({ post }) {
console.log("in render", post);
return (
<Layout title={post.name}>
<pre>{JSON.stringify(post, undefined, 2)}</pre>
</Layout>
);
}
export async function getServerSideProps({ query }) {
return fetch(
`${process.env.API_URL}/api/post?id=${query.id}`
)
.then(result => result.json())
.then(post => ({ props: { post } }));
}
export default Post;
当我直接加载 /post/2
时,它按预期工作,但是当我通过单击从 /posts
转到 /post/2
时在链接上:
When I directly load /post/2
it works as expected but when I go from /posts
to /post/2
by clicking on a link:
<Link
as={`/post/${post.id}`}
href={`/post?id=${post.id}`}
>
看起来 2 秒内没有任何反应(api延迟) 然后内容显示.我可以在网络选项卡中看到 _next/data/development/post/9.json
正在由 fetchNextData.
It looks like nothing happens for 2 seconds (the api delay) and then the content shows. I can see in the network tab that _next/data/development/post/9.json
is being loaded by fetchNextData.
当我使用 next/Link
从一条路线移动到另一条路线时,我想显示一个加载微调器,但我在 getServerSideProps 上找不到任何允许我这样做的文档.
I would like to show a loading spinner when I move from one route to another using next/Link
but I can't find any documentation on getServerSideProps that allows me to do this.
当我直接转到 /post/:id
时,我希望在服务器端获取数据并获得完全呈现的页面(有效),但是当我移动到另一条路线时,数据应该从客户端获取(作品).然而;我想要一个加载指示器,并且在数据请求期间不让 UI 冻结.
When I directly go to /post/:id
I'd like the data to be fetched server side and get a fully rendered page (works) but when I then move to another route the data should be fetched from the client (works). However; I would like to have a loading indicator and not have the UI freeze up for the duration of the data request.
推荐答案
你可以使用 nprogress 在你的 _app.js
You can use nprogress in your _app.js
import NProgress from 'nprogress';
import "nprogress/nprogress.css";
import Router from 'next/router';
NProgress.configure({
minimum: 0.3,
easing: 'ease',
speed: 800,
showSpinner: false,
});
Router.events.on('routeChangeStart', () => NProgress.start());
Router.events.on('routeChangeComplete', () => NProgress.done());
Router.events.on('routeChangeError', () => NProgress.done());
或动态导入到 _app.js
以减小包大小
or dynamic import to _app.js
to reduce bundle size
ProgessBar.js
import Router from 'next/router';
import NProgress from 'nprogress';
NProgress.configure({
minimum: 0.3,
easing: 'ease',
speed: 500,
showSpinner: false,
});
Router.events.on('routeChangeStart', () => NProgress.start());
Router.events.on('routeChangeComplete', () => NProgress.done());
Router.events.on('routeChangeError', () => NProgress.done());
export default function () {
return null;
}
_app.js
import "nprogress/nprogress.css";
import dynamic from 'next/dynamic';
const ProgressBar = dynamic(() => import('components/atoms/ProgressBar'), { ssr: false });
const App = () => {
...
return <>
...
<ProgressBar />
</>
}
这篇关于nextjs getServerSideProps 显示加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!