问题描述
我尝试使用 React 上下文管理我的应用程序的登录状态。逻辑很简单:如果用户在登录页面通过认证,则上下文中的登录状态应该更新为true
,用户将被引导到首页。我还使用登录状态和 Redirect
来阻止用户访问登录页面。
遗憾的是,此方法未能阻止登录用户查看登录页面。原因是一旦用户成功登录并被重定向到这里,登录状态就会变回 false
。我觉得我一定做错了什么,但无法弄清楚。
这是我的 React Context 设置:
// LoginContext.js
export default React.createContext({
isAuthenticated: null,logoutUser: () => {},loginUser: () => {}
})
这是我放置上下文提供程序的应用程序组件:
//App.js
class App extends Component {
state = {
users: [],isAuthenticated: false
};
logoutUser = () => {
this.setState({ accesstoken: null,username: null,isAuthenticated: false });
};
loginUser = () => {
this.setState({ isAuthenticated: true })
}
render() {
const value = {
isAuthenticated: this.state.isAuthenticated,logoutUser: this.logoutUser,loginUser: this.loginUser
}
return (
<LoginContext.Provider value={value}>
<div>
<Switch>
<Route
exact path="/"
render={() => (
<HomePageScreen
data={homepage_data}
recordImpression={this.recordImpression}
/>
)}
/>
<Route path="/login">
{value.isAuthenticated
? <Redirect to="/" />
: <LoginScreen
handleLoginFormSubmit={this.handleLoginFormSubmit}
recordImpression={this.recordImpression}
/>}
</Route>
</Switch>
</div>
</LoginContext.Provider>
}
handleLoginFormSubmit = async (data,bannerID = '') => {
const url = `${process.env.REACT_APP_SERVICE_URL}/users/login`;
try {
const res = await axios.post(url,data)
.then(res => {
this.setState({ accesstoken: res.data.access_token,username: data.username });
this.loginUser()
this.props.history.push('/',{ newLogin: true });
// the line below saves the refresh_token to the local storage of the browser
window.localStorage.setItem("refreshToken",res.data.refresh_token);
window.localStorage.setItem("username",data.username);
})
} catch (error) {
if (bannerID) {
window.scrollTo(0,0)
this.displayBanner(bannerID)
}
}
};
解决方法
如果在上下文中声明另一个状态变量可以跟踪重定向是第一次发生还是重定向已经发生的天气怎么办?