无法在Redux中访问auth状态

ws51t4hk  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(140)

我不明白为什么我得到未定义的错误,有人可以帮助我解决为什么我无法访问身份验证状态?
src/queries/authSlice.jsx:

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

const initialState = {
    isAuthenticated: false,
}

const authSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
        loginSuccess: (state) => {
            state.isAuthenticated = true;
        },
        logoutSuccess: (state) => {
            state.isAuthenticated = false;
        }
    }
});

export const selectUser = (state) => console.log(state.auth)
export const { loginSuccess, logoutSuccess } = authSlice.actions;
export default authSlice.reducer;

字符串
我得到错误Auth State: undefined
src/queries/rootReducer.jsx:

import { combineReducers } from 'redux';
import authReducer from './authSlice';
import { queriesApi } from './queries';

const rootReducer = combineReducers({
    auth: authReducer,
    [queriesApi.reducerPath]: queriesApi.reducer
});

export default rootReducer;


src/queries/store.jsx:

import { configureStore } from '@reduxjs/toolkit';
import { queriesApi } from './queries';

const store = configureStore({
    reducer: {
        [queriesApi.reducerPath]: queriesApi.reducer
    },
    middleware: (getDefaultMiddleware) => {
        return getDefaultMiddleware().concat(queriesApi.middleware)
    }
});

export default store;


SignIn.jsx代码:

import * as React from 'react';
import { ThemeProvider } from '@mui/material/styles';
import { useDispatch, useSelector } from 'react-redux';
import { loginSuccess, logoutSuccess, selectUser } from '../queries/authSlice';

const defaultTheme = createTheme();

export default function SignIn() {
const data = new FormData(event.currentTarget);
    console.log({
      email: data.get('email'),
      password: data.get('password'),
    });
  };

  const dispatch = useDispatch();
  const authState = useSelector(selectUser);
  console.log('Auth State:', authState);

  const isAuthenticated = authState.isAuthenticated;

  const handleLogin = () => {
    dispatch(loginSuccess());
  };

  const handleLogout = () => {
    dispatch(logoutSuccess());
  };

  return (
    <ThemeProvider theme={defaultTheme}>
      <div>
      {isAuthenticated ? (
        <button onClick={handleLogout}>Logout</button>
      ) : (
        <button onClick={handleLogin}>Login</button>
      )}
    </div>
    </ThemeProvider>
  );
}

**更新:我已经添加了登录页面,其中Auth State:undefined正在控制台中生成,但问题是:

我不明白为什么在这一行导出const selectUser =(state)=> console.log(state.auth)state.auth会生成未定义的输出?

eimct9ow

eimct9ow1#

在调用configureStore函数时,应将rootReducer传递给reducer选项。
authSlice.ts

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

const initialState = {
  isAuthenticated: false,
};

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    loginSuccess: (state) => {
      state.isAuthenticated = true;
    },
    logoutSuccess: (state) => {
      state.isAuthenticated = false;
    },
  },
});

export const selectUser = (state) => state.auth;
export const { loginSuccess, logoutSuccess } = authSlice.actions;
export default authSlice.reducer;

字符串
queries.ts

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

type Pokemon = any;

export const pokemonApi = createApi({
  reducerPath: 'pokemonApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
  endpoints: (builder) => ({
    getPokemonByName: builder.query<Pokemon, string>({
      query: (name) => `pokemon/${name}`,
    }),
  }),
});

export const { useGetPokemonByNameQuery } = pokemonApi;


rootReducer.ts

import { combineReducers } from 'redux';
import authReducer from './authSlice';
import { pokemonApi } from './queries';

const rootReducer = combineReducers({
  auth: authReducer,
  [pokemonApi.reducerPath]: pokemonApi.reducer,
});

export default rootReducer;


store.ts

import { configureStore } from '@reduxjs/toolkit';
import { pokemonApi } from './queries';
import rootReducer from './rootReducer';

const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) => {
    return getDefaultMiddleware().concat(pokemonApi.middleware);
  },
});

export default store;


App.tsx

import { FC } from 'react';
import { useSelector } from 'react-redux';
import { selectUser } from './authSlice';
import { useGetPokemonByNameQuery } from './queries';

import './style.css';

export const App: FC<{ name: string }> = ({ name }) => {
  const authState = useSelector(selectUser);
  console.log('Auth State:', authState);

  const state = useSelector((state) => state);
  console.log('state: ', state);

  const { data, error, isLoading } = useGetPokemonByNameQuery('bulbasaur');
  console.log(data, error, isLoading);

  return (
    <div>
      <h1>Hello {name}!</h1>
      <p>Start editing to see some magic happen :)</p>
    </div>
  );
};


控制台日志:


的数据
完整示例:stackblitz

相关问题