反应:页面加载后第一次导航时,location.state是未定义的 [英] React: location.state is undefined on first time navigating after page load
问题描述
我有一个React组件,它显示一个链接:
I have a React component, which display a Link:
Magic.tsx:
const { message } = this.props;
<Link to={ { pathname: HOGWARTS, state: { message } } }>
Go to Page
</Link>
我正在将此Magic
组件作为Prop传递给另一个组件,在其中我以动态message
状态对其进行迭代
I am passing this Magic
Component as a Prop to another component, where I am iterating over it, with Dynamic message
state
Parent.tsx
const CustomComp = this.props.Magic;
const content = messageArray.map(msg => <CustomComp message={ msg } />)
{ content } //Render all the Links with message state
这将正确呈现链接.但是,当我单击链接并调试HOGWARTS
页时,location.state是未定义的.
如果返回上一页,然后再次单击,则location.state正确,具有message
数据.
因此,在某种程度上它不适用于页面加载,但是在第二次单击后,它可以正常工作.
This is rendering the Link correctly. But when I click on the Link and debug the HOGWARTS
page, the location.state is undefined.
If go back to previous page, and click again, the location.state is correct, having message
data.
So somehow it's not working on page load, but after clicking on second time, it works.
有人遇到过同样的问题吗?
Did anyone faced the same issue?
注意:我已经使用React Devtool
检查了<Link />
标签,在侧边栏显示了message
状态附加到了此链接.
Note: I've inspected the <Link />
tag using React Devtool
, on sidebar it shows that, what message
state is attached to this link.
推荐答案
'state'匹配'BrowserRouter','hash'匹配'HashRouter',因此,如果您使用'HashRouter'匹配'hash',则'state'必须为未定义
’state‘ match 'BrowserRouter','hash' match 'HashRouter',so if you use 'HashRouter' match 'hash', 'state' must be undefined
这篇关于反应:页面加载后第一次导航时,location.state是未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!