【发布时间】: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 未定义。