在next.js中触发客户端重新加载

时间:2018-12-12 09:30:40

标签: node.js next.js

场景

索引页面使用“ getInitialProps”加载数据。然后,我们创建一个可以创建新数据的对话框。创建新数据后,应重新加载当前页面。

问题

我们使用Router.replace('/')重新加载页面。但这会触发服务器端渲染。

问题

我们需要的是客户端重新加载。应该在浏览器中调用“ getInitialProps”函数。那么,如何进行客户端重新加载?

4 个答案:

答案 0 :(得分:9)

最后一个答案是与该主题不正确或无关

如果您实际上使用了Router.push(),则您更改了路线。

您没有重新加载它。

假设用户在

http://www.example.com/profile

并使用

修改配置文件

Router.replace('/')

您将被带到

http://www.example.com/http://www.example.com/profile页面未重新加载。

解决方案

如果是这种情况,则必须使用Router.reload();

记住,您必须像这样import Router from "next/router";

导入路由器对象

有关更多信息:https://nextjs.org/docs/api-reference/next/router#routerreload

答案 1 :(得分:3)

没有找到我真正想要的答案,

这对我有用:

import Router from 'next/router'

Router.reload(window.location.pathname);

答案 2 :(得分:1)

运行以下代码

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在服务器上仅渲染一次。我可以看到isServer在“重新加载”之后也等于false。

您如何准确地重新加载页面,以便看到它在服务器端呈现?

PS

以下是屏幕截图:

答案 3 :(得分:1)

更好的选择是使用 router.replace(router.asPath)

replace 不会创建新的历史记录项,因此返回按钮按预期工作

本文详细解释 https://www.joshwcomeau.com/nextjs/refreshing-server-side-props/

相关问题