型別錯誤
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"
},
}
我是一個非常初學者,我通過觀看在線講座來學習。我不太明白為什么在這個短代碼中出現錯誤。
uj5u.com熱心網友回復:
router.query默認情況下是一個空物件{},所以之后const { all } = router.query;,all是undefined。你不能打電話join的undefined,因為錯誤是告訴你。真正的問題是 OP 正在導航到“localhost:3000/post/hello/world”,但仍然出現空指標例外。原因是組件用空物件預渲染,然后用陣列再次渲染。此行為在下面鏈接的檔案中。“如果頁面沒有資料獲取要求,它[查詢] 在預渲染期間將是一個空物件。” 所以 OP 需要的只是一個空檢查。
對于檔案router是在這里
return (
<div>
<h1>Post: {all && all.join("/")}</h1>
</div>
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/400366.html
標籤:javascript 反应 加入 下一个.js 类型错误
