Javascript 反应:加载页面后首次导航时未定义location.state
我有一个React组件,它显示一个链接: Magic.tsx:Javascript 反应:加载页面后首次导航时未定义location.state,javascript,reactjs,react-router,location,Javascript,Reactjs,React Router,Location,我有一个React组件,它显示一个链接: Magic.tsx: const { message } = this.props; <Link to={ { pathname: HOGWARTS, state: { message } } }> Go to Page </Link> 这将正确呈现链接。但是当我点击链接并调试霍格沃茨的页面时,location.state是未定义的。 如果返回上一页并再次单击,则location.state是正确的,具有消息数据。 所以不知
const { message } = this.props;
<Link to={ { pathname: HOGWARTS, state: { message } } }>
Go to Page
</Link>
这将正确呈现链接。但是当我点击链接并调试霍格沃茨的页面时,location.state是未定义的。
如果返回上一页并再次单击,则location.state是正确的,具有消息
数据。
所以不知何故,它在页面加载时不起作用,但在第二次点击后,它就起作用了
有没有人面临同样的问题
注意:我已经使用
React Devtool
检查了
标记,在侧栏上它显示了该链接附加了什么消息
状态。您只需要处理您的状态:{message}未定义的情况,如下所示,因为只有单击链接时状态才可用
因此,location.state
在初始时未定义
在Parent.tsx中
你可以这样做
const message =
(this.props.location.state && this.props.location.state.message) != undefined
? this.props.location.state.message
: " ";
然后使用它
const content = messageArray.map(msg => <CustomComp message={ msg } />)
const content=messageArray.map(msg=>)
这应该对您有所帮助:) 'state'匹配'BrowserRouter','hash'匹配'HashRouter',因此如果使用'HashRouter'匹配'hash','state'必须是未定义的
const content = messageArray.map(msg => <CustomComp message={ msg } />)