在React中实现PrivateRoute时遇到一些问题。这是我的代码:
class App extends Component {
constructor(props) {
super(props);
this.state = {
currentUser: null,
loadingUser: true
}
}
componentDidMount() {
this.onAuth();
};
onAuth = () => {
getCurrentUser().then((json) => {
console.log(json);
this.setState({
currentUser: json,
loadingUser: false
})
}).catch((error) => {
this.setState({
currentUser: null,
loadingUser: false,
})
})
};
logout = () => {
logout();
this.setState({
currentUser: null,
loadingUser: false
});
this.props.history.push("/");
toast.info("Succesfully logout.");
};
render() {
return (
<div className="body">
<ToastContainer closeOnClick={false}/>
<ApplicationHeader currentUser={this.state.currentUser} logout={this.logout}/>
<Grid>
<div className="app-content">
<Switch>
<Route exact path="/vote/:id" render={(props) => <Vote currentUser={this.state.currentUser} {...props}/>}/>
<Route exact path="/login" render={() => <Login onAuth={this.onAuth} />}/>
<PrivateRoute authed={this.state.currentUser != null} exact path="/vote" component={NewProcess} />
<PrivateRoute authed={this.state.currentUser != null} exact path="/items" component={NewItems} />
<Route component={NotFound}/>
</Switch>
</div>
</Grid>
<Footer/>
</div>
);
}
}
const PrivateRoute = ({component: Component, authed, ...rest}) => {
return (
<Route
{...rest}
render={(props) => authed === true
? <Component {...props} />
: <Redirect to={{pathname: '/login', state: {from: props.location}}} />} />
)
}
当用户发布凭据(或呈现App主组件)时,将调用onAuth方法并设置(或不设置)App状态的currentUser
属性。此属性为null(当用户未通过身份验证时),并且表示诸如id和username之类的用户详细信息(当用户通过身份验证时)。然后,在基于该属性组件的PrivateRoute中,或者应用程序将用户重定向回登录页面。而且效果不佳。我的意思是,当我已经通过身份验证并尝试访问任何私有路由时,我将重定向到适当的组件。问题在两种情况下发生:
当currentUser
属性更改时,似乎似乎无法刷新PrivateRoute组件,这有点奇怪,因为我在ApplicationHeader中使用了类似的方法来在用户通过身份验证时显示用户名(并且正确刷新了)。
那么,我在这里做错了什么?
答案 0 :(得分:0)
我根据条件渲染了路由或重定向,并且对我有用。
类似以下内容:
class PrivateRouteComponent extends React.Component{
render(){
return (
this.props.isAuthenticated===true?
(
<Route path={this.props.path} render={this.props.component} />
):
(<Redirect to={{
pathname: '/login',
state: { from: this.props.path }
}} />));
}
}