场景
索引页面使用“getInitialProps”加载数据。然后我们创建一个对话框,可以创建新的数据。创建完新数据后,应该重新加载当前页面。
问题
我们使用Router.replace('/')
重新加载页面。但这会触发服务器端渲染。
问题
我们需要的是客户端重新加载。"getInitialProps"函数应该在浏览器中被调用。那么,如何进行客户端重新加载?
http://www.example.com/profile
页面上编辑了个人资料,并出于某种原因,您需要重新加载相同的页面。如果您的情况类似于此,则可以使用 Router.reload();
方法。请记住,您必须像这样导入 Router 对象: import Router from "next/router";
。更多信息请参见:https://nextjs.org/docs/api-reference/next/router#routerreload。router.replace(router.asPath)
replace不会创建新的历史记录,因此返回按钮可以按预期工作。import { useRouter } from "next/navigation";
export default function Component(){
const router = useRouter();
router.replace(router.asPath);
}
router.asPath
应该是 router.replace()
的默认参数。 - Jim Jin从NextJs 13版本开始,新的路由对象具有refresh()
方法,它允许您在客户端刷新(重新获取)数据而无需进行完整的页面重新加载。
可以像以下方式使用:
import { useRouter } from "next/navigation";
export default function Component(){
const router = useRouter();
//this will reload the page without doing SSR
router.refresh();
}
router.reload()
,也就是说,像一个初始请求 - 在服务器上真正重新创建页面并由浏览器加载响应 - 非常慢。使用router.replace(router.asPath)
似乎只重新获取页面属性并根据需要替换更改的DOM分支 - 速度更快。 - jelmd没有看到真正符合我需求的答案,
这个对我有用:
import Router from 'next/router'
Router.reload(window.location.pathname);
pages/index.js
import Router from 'next/router';
function Index({ isServer }) {
console.log('render', new Date());
return (
<div>
<h1>Home page. Is it on server? - {isServer ? 'Yes' : 'No'}</h1>
<button type="button" onClick={() => Router.push('/')}>
Reload me
</button>
</div>
);
}
Index.getInitialProps = async ({ req }) => {
return { isServer: !!req };
};
export default Index;
console.log
一次。我还可以看到,在“reload”后,isServer
也等于false。Router.replace('/')
(客户端渲染)可以正常工作。然而,在生产环境中,它会触发服务器端渲染。我可以在浏览器的调试窗口中看到网络访问。本地环境和生产环境之间唯一的区别是生产环境中有nginx和资源前缀。这非常奇怪。 - Jim Jinrouter.push(window.location.href);
router.refresh();
router.refresh();
可以吗? - Jim Jinrouter.refresh()
在我的端上没有起作用。 - Devdreamsolutionrouter.push(window.location.href);
是否会触发服务器负载? - Jim Jinwindow.location.reload()
。如果你正在使用nextjs Link,它会预加载页面。如果你需要默认的重新加载,你需要使用一个标签而不是Link。
getInitialProps
只能在服务器端渲染时调用,您可以在客户端上始终调用componentDidMount
。 - Agney