React: location.state is undefined on first time navigating after page load

荒凉一梦 提交于 2019-12-11 17:24:25

问题


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>

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

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?

Note: I've inspected the <Link /> tag using React Devtool, on sidebar it shows that, what message state is attached to this link.


回答1:


’state‘ match 'BrowserRouter','hash' match 'HashRouter',so if you use 'HashRouter' match 'hash', 'state' must be undefined




回答2:


You just need to handle your state: { message } undefined case like below , as the state will be available only when the Link is clicked

So location.state is undefined at initial .

In your Parent.tsx

You can do something like this ..

const message =
            (this.props.location.state && this.props.location.state.message) != undefined
                ? this.props.location.state.message
                : " ";

And then use it

const content = messageArray.map(msg => <CustomComp message={ msg } />)

This should help you .. :)



来源:https://stackoverflow.com/questions/52832085/react-location-state-is-undefined-on-first-time-navigating-after-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!