Reaction路由V5
我正在try 构建一个简单的重定向,以便当用户try 访问受限URL时,它会将他们重定向到登录,登录后,它会将他们发送回他们所在的URL.例如:WebSite.com/设置受到保护,因此如果尚未登录,请重定向至登录.登录后,重定向回设置.这一直很有效,直到我最近重新嵌套了我的路由,包括布局.我假设我的重定向URL正在到达父路由,但我不确定如何将其向下传递到组件.
App.js:
<Switch>
<Route path="/password-reset/:reset_key?" exact>
<AuthLayout>
<PasswordReset />
</AuthLayout>
</Route>
<Route path="/register" exact>
<AuthLayout>
<Register />
</AuthLayout>
</Route>
<Route path="/login" exact>
<AuthLayout>
<Login />
</AuthLayout>
</Route>
{/* Other MainLayout routes */}
<Route>
<MainLayout>
<Switch>
<Route path="/" exact component={Dashboard} />
<Route path="/search" exact component={SearchResults} />
<Route path="/user/:user_id" exact component={Profile} />
<PrivateRoute path="/settings" exact component={Settings} />
<Route path="/communities" exact component={CommunityDashboard} />
<PrivateRoute path="/communities/new" exact component={CommunityNew} />
<Route path="/communities/view/:community_id" exact component={CommunityView} />
<PrivateRoute path="/communities/edit/:community_id" exact component={CommunityEdit} />
<Route path='/404' component={Error404} />
</Switch>
</MainLayout>
</Route>
<Redirect from='*' to='/404' />
</Switch>
命中受保护的路由,将触发PrivateRouting功能:
const PrivateRoute = ({component: Component, path, auth, ...rest}) => (
<Route
{...rest}
render = {props =>
auth.isAuthenticated === true ? (
<Component {...props} />
) : (
<Redirect to={{
pathname: '/login',
state: {
redirectUrl: window.location.href.includes('login') ? '/' : window.location.href
}
}} />
)
}
/>
);
我无法在我的代码中的任何地方访问这个.state.redirectUrl.这是我正在使用的布局页面.作为路径中的第一个嵌套组件,我想我至少会在那里看到它
import React from 'react';
import './auth.css';
import PropTypes from "prop-types";
import {connect} from "react-redux";
class AuthLayout extends React.Component {
componentDidMount() {
if(this.props.auth.isAuthenticated){
this.props.history.push('/');
}
}
render() {
return (
<div className="auth-background">
<img
alt=""
className="logo"
src={require("./logo1.png")}
/>
<div id='auth-form'>
{this.props.children}
</div>
</div>
);
}
}
AuthLayout.propTypes = {
auth: PropTypes.object.isRequired
}
const mapStateToProps = (state) => ({
auth: state.auth
});
export default connect(mapStateToProps, {})(AuthLayout);
登录页嵌套在Routing>;AuthLayout下.我需要在这里访问redirectUrl,这样我就可以传递给我的登录函数,并在成功登录后重定向:
class LoginForm extends React.Component {
constructor(props){
super(props);
this.state = {
email: '',
password: '',
errors: {}
}
}
handleSubmit = values => {
const userData = {
email: values.email,
password: values.password
};
const redirectUrl = this.props.location ? this.props.location.state.redirectUrl : "/"
this.props.loginUser(userData, redirectUrl, this.props.history);
};
render() {
return (