通过本地存储的注销功能

Posted

技术标签:

【中文标题】通过本地存储的注销功能【英文标题】:Logout funcionality via local storage 【发布时间】:2021-06-24 03:44:27 【问题描述】:

所以在这里我有通过本地存储令牌登录的功能。我在开发工具/应用程序中创建用户后获得令牌,它将我重定向到正在工作的家。不工作的是这个。创建一个用户它正在工作,但是当它加载时它应该显示注销而不是登录,并且应该隐藏购物车组件。我在哪里犯错 上下文接口


import React from "react";
const UserContext = React.createContext();

function getUserFromLocalStorage() 
    return localStorage.getItem("authToken")
      ? JSON.parse(localStorage.getItem("authToken"))
      :  username: null, token: null ;
  

function UserProvider( children ) 
  const [user, setUser] = React.useState(getUserFromLocalStorage());
  
    const history = useHistory();
    const logoutHandler = () =>
      localStorage.removeItem("user");
      history.push("/")
  
  return (
    <UserContext.Provider
      value= user, logoutHandler  
    >
      children
    </UserContext.Provider>
  );


export  UserContext, UserProvider ;

登录链接

import React from "react";
import  Link  from "react-router-dom";
import  UserContext  from "../../context/user";
import  useHistory  from "react-router-dom"
export default function LoginLink() 

  const  user, logoutHandler  = React.useContext(UserContext);

  if (user.authToken) 
    return (
      <button
        onClick=() => 
          logoutHandler();
        
        className="login-btn"
      >
        logout
      </button>
    );
  
  return <Link to="/login">login</Link>;

标题

import React from 'react';
import  Link, useHistory  from "react-router-dom";
import Search from './Search';
import './Header.css'
import SearchBooks from './SearchBooks';
import LoginLink from '../Signin/LoginLink';
import CartLink from '../Cart/CartLink';
import  UserContext  from '../../context/user';

const Header = () => 
const  user  = React.useContext(UserContext);

    return (
        <div className='header__container'>
            <Link to='/'>
            <img src='/audi.png' />
            </Link>  
            <li>
              <LoginLink />
            </li>
           user.authToken &&(
            <CartLink /> 
           )    
                 
        </div>
    )


export default Header

登录组件

import  useState,  from "react";
import  useHistory  from "react-router-dom"
import axios from "axios";
import  Link  from "react-router-dom";
import "./Signin.css";

const Login = () => 
  const  user, setUser  = React.useContext(UserContext);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const history = useHistory()

  
  const loginHandler = async (e) => 
    e.preventDefault();
    const config = 
      header: 
        "Content-Type": "application/json",
      ,
    ;

    try 
      const  data  = await axios.post(
        "http://localhost:5000/api/auth/login",
         email, password ,
        config
      );

      localStorage.setItem("authToken", data.token);
      setUser(user)
      history.push("/");
     catch (error) 
      if (error.response) 
        setError(error.response.data.error);
      
      setTimeout(() => 
         setError("");
      , 5000);
    
  ;

  return (
    <div className="login-screen">
      <form onSubmit=loginHandler className="login-screen__form">
        <h3 className="login-screen__title">Login</h3>
        error && <span className="error-message">error</span>
        <div className="form-group">
          <label htmlFor="email">Email:</label>
          <input
            type="email"
            required
            id="email"
            placeholder="Email address"
            onChange=(e) => setEmail(e.target.value)
            value=email
            tabIndex=1
          />
        </div>
        <div className="form-group">
          <label htmlFor="password">
            Password:" "
            <Link to="/forgotpassword" className="login-screen__forgotpassword">
              Forgot Password?
            </Link>
          </label>
          <input
            type="password"
            required
            id="password"
            autoComplete="true"
            placeholder="Enter password"
            onChange=(e) => setPassword(e.target.value)
            value=password
            tabIndex=2
          />
        </div>
        <button type="submit" className="btn btn-primary">
          Login
        </button>

        <span className="login-screen__subtext">
          Don't have an account? <Link to="/register">Register</Link>
        </span>
      </form>
    </div>
  );
;

export default Login;

【问题讨论】:

【参考方案1】:

登录后,您只将 authToken 设置到您的 localStorage 中,而不是在您的 Provider 中。您需要在登录后调用 setUser 以便 Header 组件知道用户已登录。

【讨论】:

我已经更新了登录组件中的代码,可以吗

以上是关于通过本地存储的注销功能的主要内容,如果未能解决你的问题,请参考以下文章

如何使用php在注销时删除浏览器的本地存储项

如何在注销/注销时清除 ReactJs 中的所有商店?

Sencha Touch 存储同步

探索HTML5本地存储功能运用技巧

OTPUB知识课堂:云存储和本地存储之间的区别

Android 实现拍照功能,并将图片保存到本地存储