在我的React项目中使用redux,我保存从用户那里获得的令牌并尝试在其他组件中使用它/

问题描述 投票:0回答:1

我在一个项目中使用 redux,问题是我保存了从用户登录获得的令牌,但是当我尝试使用它的组件时它返回 null。

我使用console.log来验证它是否保存在redux存储中,但是当使用consolelog来检查是否正确提取它时,它返回null。

这是我的 Redux 商店

import { configureStore } from "@reduxjs/toolkit";
import session_slice from "./slices/session_slice";
import term_slice from "./slices/term_slice";
import login_slice from "./slices/login_slice";
import tenant_slice from "./slices/tenant_slice";


export const store = configureStore({
  reducer: {
    session: session_slice,
    term: term_slice,
    login: login_slice,
    tenant: tenant_slice,
  }
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

这部分是我试图在组件中检查它但它返回 null

import { useSelector } from 'react-redux';

const Real = () => {
  const token = useSelector(state => state.login.token);

  // Use the token for operations here
  console.log("Token in component:", token);

  return <div>My Component</div>;
}

export default Real

这是我的登录拼接,我在其中保存用户令牌和从我的 api 获取的数据。

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import login from '../../api/admin/login';

export const loginUser = createAsyncThunk('login/loginUser', async ({ email, password }, { rejectWithValue }) => {
  try {
    const data = await login(email, password);
    return data;
  } catch (error) {
    return rejectWithValue(error.message); // Capture and return the error message
  }
});

const loginSlice = createSlice({
  name: 'login',
  initialState: {
    user: null,
    token: null, // Add token to initial state
    status: 'idle',
    error: null
  },
  reducers: {
    logout: (state) => {
      state.user = null;
      state.token = null; // Clear the token on logout
    }
  },
  extraReducers: (builder) => {
    builder
      .addCase(loginUser.pending, (state) => {
        state.status = 'loading';
        state.error = null; // Clear previous errors
      })
      .addCase(loginUser.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.user = action.payload.data;
        console.log(action.payload.data)
        state.token = action.payload.data.token; // Store the token
        console.log(action.payload.data.token)
        state.error = null; // Clear previous errors
      })
      .addCase(loginUser.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.payload; // Capture error message
      });
  }
});

export const { logout } = loginSlice.actions;
export default loginSlice.reducer;
 
reactjs react-redux
1个回答
0
投票

使用本地存储来存储token

localStorage.setItem("user", JSON.stringify(response.data));
© www.soinside.com 2019 - 2024. All rights reserved.