【发布时间】:2019-11-05 04:55:01
【问题描述】:
我正在尝试实现一个私有路由组件来重定向未经过身份验证的用户。问题是当我渲染像<PrivateRoute authenticated={this.state.isAuthenticated} path='/private' component={Panel} currentUser={this.state.currentUser} 这样的组件时,私有路由会将经过身份验证的用户重定向到登录页面,而不是转到面板。
在App.js 中,我渲染了所有路由,包括<PrivateRoute/>,并在ComponentDidMount() 中设置了currentUser 和isAuthenticated 状态变量,但我无法将它们传递给PrivateRoute。
App.js
//imports...
class App extends Component {
state = {
currentUser: null,
isAuthenticated: false,
isLoading: false
}
loadCurrentUser = () => {
this.setState({
isLoading: true
});
// imported method
getCurrentUser()
.then(response => {
this.setState({
currentUser: response,
isAuthenticated: true,
isLoading: false
});
})
.catch(error => {
console.log(error)
this.setState({
isLoading: false
});
});
}
componentDidMount() {
this.loadCurrentUser();
}
handleLogin = () => {
this.loadCurrentUser();
this.props.history.push("/");
}
render () {
return (
<React.Fragment>
<Navigation
currentUser={this.state.currentUser}
isAuthenticated={this.state.isAuthenticated}
handleLogout={this.handleLogout} />
<Switch>
<PrivateRoute
authenticated={this.state.isAuthenticated}
exact
path='/postulante'
component={Panel}
currentUser={this.state.currentUser} />
<Route
exact
path='/'
render={
(props) => <Landing {...props} />
} />
<Route
path="/login"
exact
render={
(props) => <Login onLogin={this.handleLogin} {...props} />
} />
</Switch>
</React.Fragment>
);
}
}
export default withRouter(App);
请注意,<Navigation /> 组件确实获得了正确的状态变量。
PrivateRoute.js
//imports...
const PrivateRoute = ({ component: Component, authenticated, ...rest }) => (
<Route
{...rest}
render={props =>
authenticated ? (
<Component {...rest} {...props} />
) : (
<Redirect
to={{
pathname: '/login',
state: { from: props.location }
}}
/>
)
}
/>
);
export default PrivateRoute
【问题讨论】:
-
嗨!刚刚给你写了一个解决方案和一个沙箱供你参考。如果您有任何问题,请告诉我:)
标签: reactjs routes react-router