TypeError: Cannot read properties of undefined (reading 'join')
TypeError: Cannot read properties of undefined (reading 'join')
TypeError
import { useRouter } from "next/router";
export default function PostAll() {
const router = useRouter();
const { all } = router.query;
return (
<div>
<h1>Post: {all.join("/")}</h1>
</div>
);
}
wait - compiling...
event - compiled client and server successfully in 32 ms (176 modules)
error - pages/post/[...all].js (9:21) @ PostAll
TypeError: Cannot read properties of undefined (reading 'join')
7 | return (
8 | <div>
> 9 | <h1>Post: {all.join("/")}</h1>
| ^
10 | </div>
11 | );
12 | }
{
"dependencies": {
"next": "12.0.7",
"react": "17.0.2",
"react-dom": "17.0.2"
},
}
我是一个初学者,我是通过看在线讲座来学习的。我不太明白为什么我在这段简短的代码中遇到错误。
router.query
默认是一个空对象{}
,所以在const { all } = router.query;
之后,all
就是undefined
。而且您不能在 undefined
上调用 join
,因为错误告诉您。真正的问题是 OP 正在导航到“localhost:3000/post/hello/world”,但仍然出现空指针异常。原因是组件使用空对象预渲染,然后使用数组再次渲染。此行为在下面链接的文档中。 “如果页面没有数据获取要求,它[查询]在预呈现期间将是一个空对象。”所以OP需要的只是一个空检查。
router
的文档是 here
return (
<div>
<h1>Post: {all && all.join("/")}</h1>
</div>
);
TypeError
import { useRouter } from "next/router";
export default function PostAll() {
const router = useRouter();
const { all } = router.query;
return (
<div>
<h1>Post: {all.join("/")}</h1>
</div>
);
}
wait - compiling...
event - compiled client and server successfully in 32 ms (176 modules)
error - pages/post/[...all].js (9:21) @ PostAll
TypeError: Cannot read properties of undefined (reading 'join')
7 | return (
8 | <div>
> 9 | <h1>Post: {all.join("/")}</h1>
| ^
10 | </div>
11 | );
12 | }
{
"dependencies": {
"next": "12.0.7",
"react": "17.0.2",
"react-dom": "17.0.2"
},
}
我是一个初学者,我是通过看在线讲座来学习的。我不太明白为什么我在这段简短的代码中遇到错误。
router.query
默认是一个空对象{}
,所以在const { all } = router.query;
之后,all
就是undefined
。而且您不能在 undefined
上调用 join
,因为错误告诉您。真正的问题是 OP 正在导航到“localhost:3000/post/hello/world”,但仍然出现空指针异常。原因是组件使用空对象预渲染,然后使用数组再次渲染。此行为在下面链接的文档中。 “如果页面没有数据获取要求,它[查询]在预呈现期间将是一个空对象。”所以OP需要的只是一个空检查。
router
的文档是 here
return (
<div>
<h1>Post: {all && all.join("/")}</h1>
</div>
);