【问题标题】:Next.js - no data in component when navigating from other routeNext.js - 从其他路线导航时组件中没有数据
【发布时间】:2020-02-06 17:13:33
【问题描述】:

我是 next.js 的新手。 我正在后端渲染我的页面视图:

module.exports = (server, app) => {
  server.get('/setup', (req, res) => {
    const testData = {
      name: "Test",
      testProp: "testVal",
    };

    return app.render(req, res, '/setup', testData);
  });
};

当我在浏览器中刷新 /setup 路由上的页面时,我可以看到 getInitialProps 中的数据,这很好。但是当我从另一条路线导航到/setup 路线时,我看不到数据。为什么会发生这种情况,如何更改它以查看数据?这是我的页面代码:

import { withAuth } from '../utils/withAuth';

const Setup = props => {
  console.log(props); // when linking there is no expected data here
  return(
    <div>Setup here</div>
  )
};

Setup.getInitialProps = async ctx => {
  return { ...ctx.query };
};

export default withAuth(Setup);

【问题讨论】:

  • 只有当路由是 '/setup' 时你才传递数据。
  • 但我正在从另一条路线导航到 /setup 路线

标签: reactjs next.js server-side-rendering


【解决方案1】:

当从其他路由导航时,你不是在服务器端渲染,所以你必须在 getInitialProps 中从服务器获取数据。

import fetch from 'isomorphic-unfetch'

const Setup = (props) => {
  console.log(props);
  return(
     <div>Setup here</div>
  )
}

Setup.getInitialProps = async (ctx) => {
  if (ctx.req) {
   // server-side
   return { ...ctx.query }
  } else {
   // client-side
   const res = await fetch('API/setup')
   const json = await res.json()
   return { ...json }
  } 
}

【讨论】:

  • 谢谢,我有相关的问题,你可以知道的答案。当我像上面那样渲染/setup 时,我在req.cookies 中看不到我当前的cookie。当我像在 axios 中那样进行标准获取时,我使用的 withCredentials 设置为 true。但是当它由服务器呈现时我看不到它。
  • 看看代码就好了,因为你提供的信息不多。也许你应该看看这个 repo:github.com/zeit/next.js/tree/canary/examples/with-cookie-auth 或许你可以从那里得到答案。
猜你喜欢
  • 1970-01-01
  • 2017-05-27
  • 2016-09-22
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
相关资源
最近更新 更多