[英]Using react-router-dom's Redirect with state
I've been following the documentation here from react-router-dom's Redirect . 我一直在关注react-router-dom的Redirect中的文档。 Right now, I have a component like that renders the following:
现在,我有一个类似的组件呈现以下内容:
return <Redirect to={{ pathname: '/login', state: { previousPath: path } }} />;
However, I'm not sure how to access previousPath
in state at my new path. 但是,我不确定如何在新路径中访问处于状态的
previousPath
。 The documentation is not clear on this. 文档尚不清楚。 How do I access
previousPath
? 如何访问
previousPath
?
One of your parent components should be Route
with props: match, location, history. 您的父组件之一应该是带有道具的
Route
:比赛,位置,历史记录。 You should be able to use the state you created with props.location.state
to access your previousPath
value. 您应该能够使用通过
props.location.state
创建的状态来访问previousPath
值。
See location in the React Router docs. 请参阅React Router文档中的位置 。
Solved it using ownProps
in mapStateToProps : 在mapStateToProps中使用
ownProps
解决了它:
In my Login
component (where the Redirect goes), I added this to my mapStateToProps
: 在我的
Login
组件(重定向所在的位置)中,我将此添加到了mapStateToProps
:
const mapStateToProps = (state, ownProps) => ({
...
previousPath: ownProps.location.state.previousPath,
});
And then in my props, now I have access to previousPath
. 然后在道具中,我现在可以访问
previousPath
。
according to https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md : 根据https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md :
<Redirect
to={{
pathname: "/login",
search: "?utm=your+face",
state: { referrer: currentLocation }
}}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.