Gatsby Link passing Props访问目标页面prop错误



我试图传递一个值到另一个页面做条件渲染,但我得到一个bug,我不能建立页面,因为位置是定义它似乎。我到处都找遍了,还是想不明白,如果您能给点建议,我将不胜感激。

原页(正常):

import { Link } from 'gatsby'
import React, { useState, useEffect } from 'react'
const ProfilePayment = ({     
return (              
<Link
to={`/pay-on-line${search ? `?c=${search}` : ''}`}
state={{ myProp: agentID }}>
)
})
export default ProfilePayment

在线付费页面-产生错误属性'state'不存在类型'Location':

import React, { useState } from 'react'
import Layout from '../components/layout/layout'
import { useEffect } from 'react'
import { useNumbers } from '../components/NumbersProvider/NumbersProvider'
import { useQueryParam } from '../hooks/useQueryParam'
const PayOnline = () => {
return (
{console.log(location.state.myProp)}
)
export default PayOnline

这是试图访问window.location.state.myProp。由于location在SSR期间不在全局作用域中,window不可用,您可能会遇到locationundefined的问题。

无论哪种方式,您在这里所指的location(window.location)可能没有state属性,这意味着访问myProp将在您试图访问undefined属性时抛出错误。

{console.log(location.state.myProp)}

你可能不是想跟着这个例子中,解构location道具和访问state道具:

const Photo = ({ location, photoId }) => {
if (location.state.fromFeed) {
return <FromFeedPhoto id={photoId} />
} else {
return <Photo id={photoId} />
}
}

找到答案了。回答任何人在未来遇到类似的问题盖茨比,Typescript和不能使用位置。在页面间传递道具时的状态

import React, { useState } from 'react'
import Layout from '../components/layout/layout'
import { useEffect } from 'react'
import { useNumbers } from '../components/NumbersProvider/NumbersProvider'
import { useQueryParam } from '../hooks/useQueryParam'
const PayOnline = ( { myProp }: any) => {
const agentProp = myProp
return (
{console.log(agentProp)}
)
export default PayOnline

帮助我的原创文章:映射typescript参数:Binding element 'contacts'隐式地有'any'type.ts

相关内容

最新更新