最近的一个需求:需要从A路由页面("/view/personal/user")携带一数组对象到B路由页面("/view/sysMng/user"),从而设置B页面的初始值。
最初想到的方法就是通过路由传参在A页面路由跳转时将数据放入state中,然后在B页面的componentDidMount生命周期函数中通过props.location.state接收
//A页面执行editRole方法进行路由跳转并携带state数据
private editRole = row => {
this.props.history.push({
pathname: "/view/sysMng/user/role/edit",
state: { roleData: row }
});
};
但是在B页面接收到的props如下:state的值始终为undefined
原因:
A组件所在的路由和B组件所在路由分别在不同的Router(HashRouter或BrowserRouter)下:
如下:
<Router>
<Switch>
<Route
exact={true}
path="/view/personal"
component={ParentA}
/>
<Route
path="/view/sysMng"
component={ParentB}
/>
</Switch>
</Router>
然后ParentA和ParentB组件中又分别包含了路由:
ParentA:
<Router>
<Switch>
<Route
exact={true}
path="/view/personal/user"
component={A}
/>
</Switch>
</Router>
ParentB:
<Router>
<Switch>
<Route
exact={true}
path="/view/sysMng/user"
component={B}
/>
</Switch>
</Router>
这样A组件和B组件的就不是在一个Router下了,这种情况下无法使用state传参
解决方法:
1.使用其他传参方式,如通过search
2.把A、B组件的路由写在同一个Router里面