类型错误:无法读取未定义的属性(读取“join”)

1 javascript join typeerror reactjs next.js

类型错误

import { useRouter } from "next/router";

export default function PostAll() {
  const router = useRouter();
  const { all } = router.query;

  return (
    <div>
      <h1>Post: {all.join("/")}</h1>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)
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 | }
Run Code Online (Sandbox Code Playgroud)
{
  "dependencies": {
    "next": "12.0.7",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },
}
Run Code Online (Sandbox Code Playgroud)

我是一个非常初学者,我通过观看在线讲座来学习。我不太明白为什么我在这段简短的代码中遇到错误。

Han*_*ang 5

router.query默认情况下是一个空对象{},所以之后const { all } = router.query;allundefined。并且您无法调用joinundefined因为错误告诉您。真正的问题是 OP 导航到“localhost:3000/post/hello/world”,但仍然出现空指针异常。原因是组件使用空对象预渲染,然后使用数组再次渲染。此行为位于下面链接的文档中。“如果页面没有数据获取要求,那么在预渲染期间,It[query] 将是一个空对象。” 所以OP需要的只是一个空检查。

的文档router这里

return (
  <div>
    <h1>Post: {all && all.join("/")}</h1>
  </div>
);
Run Code Online (Sandbox Code Playgroud)