NextJS:如何将数据从一个页面发送到另一个页面的 getInitialProps 函数

NextJS: How to send data from one page to another page's getInitialProps function

我正在尝试将数据从页面 B(登录)发送到页面 A(索引)getInitialProps,因为我需要页面 A 的 getInitProps 的密钥才能实际获取道具...

我目前正在尝试通过向自定义快速路由发送 POST 请求并使用该路由呈现页面服务器端来实现此目的,因此 getInitialProps 将 运行。但问题是浏览器不会呈现页面,即使它是在服务器端构建的。

POST 来自登录页面的请求(发生在客户端):

const headers = {'Content-type': 'application/json; charset=UTF-8'}
await fetch(`${getRootUrl()}/loadKey`, {method: "POST", body: JSON.stringify({key}), headers})

快速路线:

server.post('/loadKey', (req, res) => {
    // const {key} = req.body
    // console.log(key)
    next({dev}).render('/') //index page
})

密钥记录正常,在终端中,nextjs 说正在构建索引页面,getInitialProps 得到 运行,但浏览器上没有任何反应。没有重定向。

我试过使用 express.redirectexpress.render,我也试过强制客户端重定向,但对于前两者,当我使用 next.render;页面已构建,getInitialProps 运行s,但浏览器上没有发生重定向。当我使用 Link 或路由器强制重定向时,Index 的 getInitialProps 将不会获得从 POST 请求传入的密钥。

试试这个

server.post('/loadKey', (req, res) => {
    const {key} = req.body
    // Do whatever you need to do
    const actualPage = '/'
    const queryParams = { key }
    next({dev}).render(req, res, actualPage, queryParams)
})

现在您应该可以通过 props 在索引页面中访问 key

您的方法仅适用于服务器端呈现的页面(因为您需要使用 req),不适用于客户端。即使你让它工作一次,当你尝试导航到这条路线时,你的逻辑也可能会中断,或者你可能最终将你的应用程序的一部分变成 SPA,然后在访问此页面时进行一些刷新。

来自 nextjs 文档:

For the initial page load, getInitialProps will execute on the server only. getInitialProps will only be executed on the client when navigating to a different route via the Link component or using the routing APIs.

我过去使用过的一些可能的解决方案:

  • 将页面 B 作为组件实施,如果满足特定条件,则从页面 A 调用它。页面 B 没有 getInitialProps 但页面 A 有,而且您似乎需要了解页面 A 的 getInitialProps 才能正确呈现页面 B,那么为什么不使用单个页面呢?用户不会知道其中的区别。

  • 使用 Redux 之类的。您可以将道具的值存储在商店中,它在全球范围内可用,甚至可以用于 getInitialProps。但要小心!将道具保存到商店 before 尝试在页面 B 上访问它。页面的 getInitialProps 在 HoC 之前运行。