首页 > 解决方案 > 如何通过 Context API 使全局可访问的信息保存在本地以在刷新时保持不变?

问题描述

我正在尝试使用上下文 API 管理用户登录,这是我的 auth.js:

 const AuthContext = createContext({
    isAuthenticated: false
});

class AuthProvider extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isAuthenticated: false
        };
        this.signIn = this.signIn.bind(this);
        this.logout = this.logout.bind(this);
    }


    /**
     * signIn function
     */
    signIn() {
        setTimeout(() => this.setState({ isAuthenticated: true }), 1000);
    }

    /**
     * logOut function
     */
    logout(){
        setTimeout(()=>this.setState({isAuthenticated:false}),1000);
    }


    render() {
        return (
            <AuthContext.Provider value={{
                isAuthenticated: this.state.isAuthenticated,
                signIn: this.signIn,
                logout:this.logout,
                getStatus:this.getStatus
            }}>
                {this.props.children}
            </AuthContext.Provider>
        )
    }
}

const AuthConsumer = AuthContext.Consumer;

export {AuthProvider,AuthConsumer};

我有一些受保护的路线,这是我的 ProtectedRoute 组件:

    export default function ProtectedRoute({...props }) {

  return (
        <AuthConsumer>
          {({ isAuthenticated }) => (
            <Route
              render={() =>
                isAuthenticated ?
                <Redirect to="/" />  :
                (
                  <Route {...props} />
              )}
            />
          )}
        </AuthConsumer>
      );
}

像登录,注册组件和......这样的受保护路由将是这样的:

 <ProtectedRoute exact path="/profile" component={UserProfile}/>

现在,如果您从登录页面登录并使用登录功能,来自 AuthProvider 的isAuthenticated标志将设置为true ergo,您将无法在登录后进入登录或注册页面(它们受到 R 保护并尝试访问它们会将您重定向到主页),只要您尝试从地址栏中手动将地址栏更改为所需的路径(例如“/ login”),并且isAuthenticated标志设置为false就像之前没有发生过登录一样,一切正常,所以我的问题为什么在这种情况下它不能像承诺的那样工作,我应该怎么做才能完全保护路线?

标签: javascriptreactjsreact-context

解决方案


那是因为在更改 url 时它会重新加载将状态重新初始化为其默认状态的页面。在单页应用程序(React,vue)中,应用程序的状态在重新加载时重新初始化为默认值。

解决方案是在本地存储中保存令牌(或使用的身份验证标识符),并从本地存储初始化应用程序的状态


推荐阅读