首页 > 解决方案 > 将位置道具传递到页面会生成构建错误 - 链接组件 - 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

标签: reactjsgatsby

解决方案


出现您的问题是因为您没有在组件的所有调用中提供location(因此不提供state或属性),因此编译失败。accessPage

添加一个条件,例如:

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) {...}

您还可以locationprops解构中的默认设置为:

const Page = ( { location = {} } ) => {}

因此,如果您不发送它,它将导致一个空对象 ( {}),因此内部没有任何state属性。


推荐阅读