【发布时间】:2018-11-12 14:15:47
【问题描述】:
我在 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}}} />} />
)
}
当用户发布凭据(或应用程序主组件被渲染)时,onAuth 方法被调用并设置(或不)应用程序状态的currentUser 属性。此属性为 null(当用户未通过身份验证时)并表示用户详细信息,例如 id 和用户名(当用户通过身份验证时)。然后,在 PrivateRoute 中基于该属性组件被渲染或应用程序将用户重定向回登录页面。这并不好用。我的意思是当我已经通过身份验证并尝试访问任何私有路由时,我会被重定向到正确的组件。问题出现在两种情况:
- 登录后立即 - 应用程序不会将我重定向到组件 我想访问,我会留在登录页面上。
- 刷新页面(在浏览器中)对应于私有路由。
当currentUser 属性发生更改时,似乎 PrivateRoute 组件没有刷新,这有点奇怪,因为我在 ApplicationHeader 中使用类似的方法在用户通过身份验证时显示用户名(并且正确刷新)。
那么,我在这里做错了什么?
【问题讨论】:
标签: javascript reactjs