如何解决将 json 导入 react 应用程序,但在访问嵌套字段时未定义
我将一个 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
第一次渲染时未定义查询参数...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。