繁体   English   中英

重定向后无法访问组件中的 this.props.location

[英]Unable to access this.props.location in component after redirect

在组件 1 的某个地方,我有这个:

if (redirectToReferrer) {
    return <Redirect to={{
          pathname: "/test/new",
          state: { event: "test" }
     }} />;
}  

在我的组件 2 中,我有这个:

constructor(props){
    super(props);
    console.log(this.props.location) //undefined
}

根据文档,这应该有效。

可以通过重定向到组件中的 this.props.location.state 访问状态对象。 然后将通过路径名“/login”指向的登录组件中的 this.props.location.state.referrer 访问这个新的引用键(不是特殊名称)

为什么this.props.location未定义?

确保“/test/new”由App.js 中<Route/>组件或您定义路由的任何地方定义。

<Route path="/test/new" component={NewTestComp}/>

如果您已经定义了使用 render 方法,请确保您像这样将道具传递给您的组件。

<Route path="/test/new" render={(props) => <NewTestComp {...props}/>}/>

从技术上讲,组件直接路由如下:

<Route path="/about" component={About} />

具有由反应路由器提供的道具,例如位置,因此请确保无论您在哪里重定向,该组件都定义了路由。

升级到最新版本的 react-router-dom。 当前版本为 5.2.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM