[英]Linking to page causes re-render of entire page in NextJS
I have static pages and some dynamic pages with following page components:我有 static 页面和一些具有以下页面组件的动态页面:
pages/home.js
pages/about.js
pages/search/[term].js
To link the pages I am using next/link
.链接我正在使用的页面
next/link
。 Going from static to static pages performs pretty well.从 static 到 static 页面执行得非常好。 However, when I navigate to
pages/search/[term].js
I can see that the entire page re-renders.但是,当我导航到
pages/search/[term].js
时,我可以看到整个页面重新呈现。 This is pretty bad user experience if you are expecting the app to behave like an SPA.如果您希望应用程序表现得像 SPA,这将是非常糟糕的用户体验。 My assumption was the nextjs will render pages on server side and on all subsequent requests it will diff the components rendered with what needs to re-render and then re-render only updated components.
我的假设是 nextjs 将在服务器端呈现页面,并且在所有后续请求中,它将区分呈现的组件与需要重新呈现的组件,然后仅重新呈现更新的组件。 If this was the case though, the
Nav
component would not re-render.如果是这种情况,
Nav
组件将不会重新渲染。
Is it possible to only have changing components re-render?是否可以只重新渲染不断变化的组件? I might be doing something wrong.
我可能做错了什么。 I have tried making sure that I'm not unnecessarily changing props which may result in re-render but no luck so far.
我已经尝试确保我没有不必要地更改可能导致重新渲染但到目前为止没有运气的道具。 On Dev Tools I see 404 requests on static files which makes sense because this is a dynamic page:
http://localhost:3000/_next/static/development/pages/search/hello.js net::ERR_ABORTED 404 (Not Found)
在开发工具上,我在 static 文件上看到 404 个请求,这是有道理的,因为这是一个动态页面:
http://localhost:3000/_next/static/development/pages/search/hello.js net::ERR_ABORTED 404 (Not Found)
My layout looks like this:我的布局如下所示:
import Head from 'next/head';
import Navbar from './Navbar';
const Layout = (props) => (
<div>
<Head>
<title>Some title</title>
</Head>
<Navbar />
{props.children}
</div>
);
export default Layout;
...and a page looks something like this: ...页面看起来像这样:
import Layout from '../components/Layout';
const About = (props) => (
<Layout>
<main className="main">
<div className="container">
<h1>About</h1>
<Link href="/">Go home</Link>
</div>
</main>
</Layout>
);
export default About;
and [term].js
:和
[term].js
:
class Search extends React.Component {
static async getInitialProps({ query, req }) {
return { query };
}
render() {
const { query } = this.props;
return (<p>{JSON.stringify(query)}</p>);
}
}
export default Search;
This was an oversight with dynamic link handling.这是动态链接处理的疏忽。 NextJS was treating the link as static.
NextJS 将链接视为 static。 To handle the dynamic links I should have added the
as
attribute to Link as per documentation:为了处理动态链接,我应该根据文档将
as
属性添加到 Link :
<Link href="/search/[term]" as={`search/${term}`}>...</Link>
where the term is actual term value coming from props.其中术语是来自道具的实际术语值。 This fixed my problem.
这解决了我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.