【问题标题】:TypeError: Cannot read properties of null (reading 'accessToken')TypeError:无法读取 null 的属性(读取“accessToken”)
【发布时间】:2022-01-02 10:09:39
【问题描述】:

我已关注 Lama YouTube 视频以创建电子商务应用程序。 我尝试在本教程中未完成的管理页面上实现注销功能。我在redux中抓取了currentUser,然后将其设置为null以便注销。我成功地做到了。但是现在由于我已注销,我丢失了 accessToken,并且无法呈现我的登录页面和主管理面板。

//我的两个requestMethods.jsx

import axios from "axios";

const BASE_URL = "http://localhost:5000/api/";
const TOKEN = JSON.parse(JSON.parse(localStorage.getItem("persist:root")).user)
        .currentUser.accessToken;
console.log(TOKEN);

export const publicRequest = axios.create({
    baseURL: BASE_URL 
});


export const userRequest = axios.create({
    baseURL: BASE_URL,
    headers: {token: `Jhoncena ${TOKEN}`}
});

在此处抓取当前为空的令牌。

//我的userReducer

import { createSlice} from "@reduxjs/toolkit";

const userSlice = createSlice({
    name: "user",
    initialState: {
        currentUser: null,
        isFetching: false,
        error: false
    },
    reducers:{
        loginStart: (state)=>{
            state.isFetching = true;
        },
        loginSuccess: (state, action)=>{
            state.isFetching = false;
            state.currentUser = action.payload;
            state.error = false;
        },
        loginFailure: (state)=>{
            state.isFetching = false;
            state.error = true;
        },
        logout: (state) =>{
            state.currentUser = null;
        },
    },
});

export const {loginStart, loginSuccess,loginFailure, logout} = userSlice.actions;
export default userSlice.reducer;


//我的 apiCalls

//USER LOGIN
export const login = async (dispatch,user)=>{
    dispatch(loginStart());

    try {
        const res = await publicRequest.post("/auth/login",user)
        dispatch(loginSuccess(res.data));
    } 
    catch (err) 
    {
        dispatch(loginFailure());
        console.log(err);    
    }
}

//USER LOGOUT
export const userlogout = async(dispatch)=>{
    dispatch(logout());
}

和我的顶部栏,其中使用 onClick 功能启动注销

import React from "react";
import { NotificationsNone, Language, Settings} from "@material-ui/icons";
import "./topbar.css";
import { useDispatch } from "react-redux";
import { userlogout } from "../../redux/apiCalls";

export default function Topbar() {
  const dispatch = useDispatch();

  const handleClick = ()=>{
    userlogout(dispatch);
  }


  return (
    <div className="topbar">
      <div className="topbarWrapper">
        <div className="topLeft">
          <span className="logo">Ecoflex-Admin</span>
        </div>
        <div className="topRight">
          <div className="topbarIconContainer">
            <NotificationsNone />
            <span className="topIconBadge">2</span>
          </div>
          <div className="topbarIconContainer">
            <Language />
            <span className="topIconBadge">2</span>
          </div>
          <div className="topbarIconContainer">
            <Settings />
          </div>
          <img src="https://img.icons8.com/fluency/96/000000/admin-settings-male.png" alt="" className="topAvatar" />
          <img className="logout" src="https://img.icons8.com/ios-filled/50/000000/exit.png" alt="" onClick={handleClick}/>
        </div>
      </div>
    </div>
  );
}

这是我的登录路径目前的样子 enter image description here

【问题讨论】:

    标签: javascript reactjs redux jwt access-token


    【解决方案1】:

    而不是

    const TOKEN = JSON.parse(JSON.parse(localStorage.getItem("persist:root")).user)
            .currentUser.accessToken;
    

    写这个:

     const TOKEN = () => {
          if (
            JSON.parse(JSON.parse(localStorage.getItem('persist:root')).user)
              .currentUser.accessToken
          ) {
            return JSON.parse(JSON.parse(localStorage.getItem('persist:root')).user)
              .currentUser.accessToken;
          } else { return '' }
        };
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2022-01-12
    • 2021-12-04
    • 2021-12-17
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2022-11-17
    • 2023-01-14
    相关资源
    最近更新 更多