React - What is the best way to handle login and authentication?

后端 未结 3 2169
梦毁少年i
梦毁少年i 2020-12-04 07:07

New to react and working on an application with authentication/logging in. It currently works but feels hacked together. Right now I have my isAuthenticated sta

3条回答
  •  自闭症患者
    2020-12-04 08:02

    If you are using an application where the authentication lasts only for one session, storing it in state is enough. But do note that this means, the user will lose the authenticated status on page refresh.

    Here is an example using React Context, where we create context using createContext and use Consumer to access it across the application.

    const AuthenticationContext = React.createContext();
    const { Provider, Consumer } = AuthenticationContext;
    
    function Login(props) {
      return (
        
          {
            value=>
            
          }
        
      );
    }
    
    function Logout() {
      return (
        
          {
            value=>
            
          }
        
      );
    }
    
    function AnotherComponent() {
      return (
        
          {
            value=>{
              return value.isAuthenticated?
                

    Logged in

    :

    Not Logged in

    } }
    ); } class App extends React.Component { constructor(props) { super(props); this.login = ()=> { this.setState({ isAuthenticated: true }); } this.logout = ()=> { this.setState({ isAuthenticated: false }); } this.state = { isAuthenticated: false, login: this.login, logout: this.logout } } render() { return ( ); } } ReactDOM.render(, document.getElementById("root"));
    
    
    

    https://reactjs.org/docs/context.html#reactcreatecontext

提交回复
热议问题