微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 React Context 阻止登录状态在主页中更改

如何解决使用 React Context 阻止登录状态在主页中更改

我尝试使用 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)
      }
    }
  };

解决方法

如果在上下文中声明另一个状态变量可以跟踪重定向是第一次发生还是重定向已经发生的天气怎么办?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。