location.state与gatsby构建失败

当我state与gatsby组件一起使用Link时,当我进行测试gatsby develop但由于gatsby build出现有关undefined东西的错误而失败时,它可以工作终端显示的错误消息是WebpackError: TypeError: Cannot read property 'info' of undefined我尝试undefined通过两种不同的方式进行检查,但这是行不通的。我想不出解决该问题的方法。第一次测试:

if (!location.state.info) {
    return null
} else

第二次测试

if (typeof location.state.info === `undefined`) {
  return null
} else

索引页

import React from "react"
import { Link } from "gatsby"

import Layout from "../components/layout"

const IndexPage = () => (
  <Layout>
    <Link to="/page_test/" state={{ info: "test" }}>
      Test
    </Link>
  </Layout>
)

export default IndexPage

import React from "react"
import { Link } from "gatsby"

const TestPage = ({ location }) => {
  return <div>{location.state.info}</div>
}

export default TestPage
费兰·布埃鲁

什么undefinedlocation.state,不是info国家本身。更改条件,您的代码应该可以工作。

if (typeof location.state === `undefined`) {}

这是使用解构的一些方法(相同的想法):

const TestPage = ({ location }) => {
  const { state = {} } = location
  const { info } = state

  return info ? (
    <div>{info}</div>
  ) : (
    <div>Other content</div>
  )
}

export default TestPage

基本上,通过销毁,您可以简化工作。这是您在中使用的({ location })默认情况下,props它们通过React中的页面和组件传递,因此({ location })等于(props)和然后props.location这只是输入对象的嵌套属性的一种方法。

同样,一旦拥有props.location(或location在中进行了重组props),您可以:

 const { state = {} } = location //equals to location.state

在上述情况下,您正在破坏结构,{}如果中没有state嵌套对象,则将默认值设置为empty(location

以相同的方式:

  const { info } = state //equals to state.info

如果state由于先前的破坏而为空,则info也将为空,如果不是,则其值为state.info因此,您的return方法可以是布尔条件,例如:

  return info ? (
    <div>{info}</div>
  ) : (
    <div>Other content</div>
  )

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Gatsby网站的Netlify构建失败

Gatsby 构建失败 google-fonts

Netlify部署在Gatsby构建上失败

如何检测window.location是否失败?

在 Gatsby Helmet 中使用 Location 道具时出错

netlify 部署构建对于 gatsby-contentful 站点失败

az acr 构建需要 <SOURCE_LOCATION> 参数

powershell:函数内的Set-Location / cd失败

window.location.reload(); 除非加上警报,否则失败

在Android浏览器上window.location失败

如何在刷新时清除props.location.state?

反应路由器:this.props.location.state为null

在渲染方法中反应无法读取this.props.location.state”

无法在UI reactjs中呈现this.props.location.state的对象

如何在 svelte-sapper 中获取 location.state

反应路由器中 location.state 的类型或接口

将mapbox-gl-geocoder添加到gatsby.js时,gatsby构建失败

Gatsby构建失败,因为在React挂钩中未定义窗口

为页面构建静态HTML失败-Gatsby和p5js

Laravel 异常属性 [location] 在 Eloquent 构建器实例中不存在

$ location的概念

AngularJS和PhoneGap:$ location.path导致随后的tempateUrl查找失败

反应:什么意思“重定向到 { pathname: '/', state: { from: props.location }

如何在页面重新加载时清除react-router中的location.state?

为什么我的状态变量未为 props.location.state 定义?

从Location.State分配时,反应状态值未定义

刷新页面后如何保持props.location.state?(不使用本地storagre)

this.prop.state.location.url是否未定义?反应Js链接道具

在TypeScript中从React.router.dom添加到props.location.state的类型