【问题标题】:Nextjs getInitialProps query.id is undefinedNextjs getInitialProps query.id 未定义
【发布时间】:2021-09-15 07:02:31
【问题描述】:

我试图从 http//localhost:3000/portfolios/helloworld 的路由中获取 id,所以 id 是 helloworld。但我收到一条错误消息,提示 TypeError: Cannot destructure property 'id' of 'query' as it is undefined.


const PortfolioDetail = ({ query }) => {
  const { id } = query;
  return <h1>I am Details Page with ID: {id}</h1>;
};

PortfolioDetail.getInitialProps = ({ query }) => {
  return { query };
};

export default PortfolioDetail;

我用类组件尝试了同样的事情,但错误是一样的。

// class PortfolioDetail extends React.Component {
//   static getInitialProps({ query }) {
//     return { query };
//   }

//   render() {
//     const id = this.props.query.id;
//     return <h1>I am Detail Page with id : {id} </h1>;
//   }
// }

// export default PortfolioDetail;

这是我的项目结构,您可以在下图看到

它只有效,我可以使用下面显示的 useRouter 获取我的 ID。

import { useRouter } from 'next/router';
import React from 'react';

const PortfolioDetail = () => {
  const router = useRouter();
  const id = router.query.id 
  return <h1>I am Details Page with ID: {id}</h1>;
};

PortfolioDetail.getInitialProps = ({ query }) => {
  return { query };
};

export default PortfolioDetail;

我被困在这一点上,我真的很想知道为什么它不起作用。

【问题讨论】:

  • 也许您在自定义_app.js 中做了一些奇怪的事情?您需要将pageProps 传递给那里的Component,您这样做了吗?
  • `导入'../styles/index.scss';导入'bootstrap/dist/css/bootstrap.min.css'; const MyApp = ({ Component, ...pageProps }) => { return ; };导出默认 MyApp; ` 这是我的 _app.js
  • 嗯,那很奇怪。我用你的代码做了一个简单的例子,它工作得很好codesandbox.io/s/…
  • 是的。你证明了我在本地环境中使用 nextjs 一定有问题。否则,无论我做什么,都没有理由使该 id 未定义。

标签: reactjs next.js


【解决方案1】:

为什么不像下面显示的代码那样使用它

  export default function FirstPost({ id }) {
    console.log("-->", id);
    return (
      <>
        {id}sdlfdfdlkj
      </>
    );
  }

  FirstPost.getInitialProps = ({ query }) => {
    return { id: query?.id };
  };

【讨论】:

  • 它再次未定义。这一定是下面的一些原因。
【解决方案2】:

我知道了,您的_app 中有错误:


import '../styles/index.scss';
import 'bootstrap/dist/css/bootstrap.min.css';

// Don't need to spread pageProps here
const MyApp = ({ Component, ...pageProps }) => {
  return <Component {...pageProps} />;
};

export default MyApp;

应该是:

const MyApp = ({ Component, pageProps }) => {
  return <Component {...pageProps} />;
};

【讨论】:

  • 非常感谢。你填补了我内心的巨大空白 :) 为什么我要在 MyApp 参数上传播 pageProps ......从现在开始我永远不会忘记这个错误。 :)
猜你喜欢
  • 2020-07-13
  • 1970-01-01
  • 2020-06-05
  • 2020-05-21
  • 2019-09-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-19
  • 2019-10-12
相关资源
最近更新 更多