reactjs - 将位置道具传递到页面会生成构建错误 - 链接组件 - Gatsby
问题描述
阅读文档后,我发现 Gatsby 具有内置功能,可以使用道具将道具 a 传递到其链接组件中的页面state
。在开发环境中,一切都按预期工作,并且在从下面的组件导航时,任何页面总是使用传递的道具正确呈现。但是,在构建过程中,我收到一个错误Building static HTML failed for path "/page/", WebpackError: TypeError: Cannot read property 'access' of undefined
,该页面内的任何location.state
调用都会发生同样的情况。
链接组件
const data = {
title: "Hello Guys",
date: "23 November 2020"
}
<Link
to="/form"
state={{
access: true,
title: data.title,
date: data.date
}}
> Proceed
</Link>
页
const Page = ( { location } ) => {
if (location.state.access === true) {
return (
<>
<div>{location.state.title}</div>
<div>{location.state.date}</div>
</>
)}
else {
return <div>Nada</div>
}
}
export default Page
解决方案
出现您的问题是因为您没有在组件的所有调用中提供location
(因此不提供state
或属性),因此编译失败。access
Page
添加一个条件,例如:
const Page = ( { location } ) => {
if (location && location.state && location.state.access) {
return (
<>
<div>{location.state.title}</div>
<div>{location.state.date}</div>
</>
)}
else {
return <div>Nada</div>
}
}
export default Page
如果您使用的是可选链接提案,您可以:
if (location?.state?.access) {...}
您还可以location
将props
解构中的默认设置为:
const Page = ( { location = {} } ) => {}
因此,如果您不发送它,它将导致一个空对象 ( {}
),因此内部没有任何state
属性。
推荐阅读
- java - 在没有 JPQL 的情况下连接两个表
- r - 如何从一个数据集中获取 R 中的频率表,使用间隔和中断形成不同的数据集?
- faunadb - 从两个日期之间的 Fauna 集合中选择满足另一个条件的文档
- kotlin - Kotlin Coroutine Scope:如果在控制器端点中使用,return@runBlocking 是否存在问题
- python - Python 基于连接条件的字典连接列表
- javascript - 视差滚动和交替文本同时
- html - 仅在右侧对齐一个链接,flex-end 不起作用
- r-markdown - 如何在 Rmarkdown 中居中和删除图形标题
- vue.js - Getting all ids/values in a form in vuejs
- flutter - Flutter ListView 不会占用所有空间