繁体   English   中英

如何使用重定向将道具传递到路线

[英]How to pass props to routes using redirect

我正在一个reactjs项目上,现在我必须将props从组件A传递到组件B,组件A在render函数中具有以下代码:

 {this.state.showComponentedit ? <div> <Redirect to={'/editB'} editdata={this.state.feedData} />: null </div> } 

我正在使用以下代码在B组件中通过B传递当前数据:

 // inside a random function which will be invoked on button press console.log("Props from B", this.props.edidata); 

edidata在组件A中为null。当我调用路由“ editB”并在组件B中使用该值时,如何获得该值。谢谢

您还可以像这样将一个对象传递给Redirect的'to'属性:

<Redirect to={{
  pathname='/editB'
  state={
    editdata: this.state.feedData
  }
}}/>

之后,在editB组件中,您可以从以下位置获取数据:

this.props.location.state

我希望这种方法可以解决您的问题。

首先,您必须使A可以访问B中的数据

您可以通过将数据提升到父组件,然后使用Route将该数据传递给A来实现。

 <Route
   exact={true}
   path="/mycomponent"
   render={props => <EditComponent editData={this.state.feedData} />}
 />

也许您可以这样做:

<Redirect
  to={{
    pathname: "/login",
    search: "?utm=your+face",
    state: { referrer: currentLocation }
  }}
/>

可以通过B组件中的this.props.location.state访问状态对象。

更多详细信息: https : //reacttraining.com/react-router/web/api/Redirect/to-object

暂无
暂无

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

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