将 json 导入 React 应用程序,但在访问嵌套字段时未定义

import json into react app but it's undefined when accessing a nested field

我将一个 json 文件导入到我的 React 应用程序中(使用 next.js 路由器),并且需要通过 URL 中的参数访问其中的一个字段。当我从另一个页面 (/home -> /annotations/<some id>) 导航时它有效,但当我刷新页面 (/annotations/<some id>) 或直接访问它时它不起作用。

JSON:

{
  "page1-9.svg": {
    "points": [
      ...
    ],
    "viewBox": "0 0 191.2066944434739 163.20512234635925"
  },
...
}
import tangrams from "../../assets/tangrams.json";
//..other imports

export default function Annotations(props) {
  const classes = useStyles();
  const router = useRouter();
  const { tangramId } = router.query;

  console.log(tangrams[tangramId]); // this always works
  console.log(tangrams[tangramId]["viewBox"]); // server error: TypeError: Cannot read property 'viewBox' of undefined
  return (...

如果我只访问 tangrams[tangramId],它工作正常,但如果我访问 tangrams[tangramId]["viewBox"],它会抛出 server error: TypeError: Cannot read property 'viewBox' of undefined

知道为什么会这样吗?

搜了一下,好像跟这个有关:github.com/vercel/next.js/discussions/11484

查询参数在第一次呈现时未定义...