简体   繁体   English

在状态下使用react-router-dom的Redirect

[英]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

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

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