我不明白为什么我得到未定义的错误,有人可以帮助我解决为什么我无法访问身份验证状态?
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会生成未定义的输出?
1条答案
按热度按时间eimct9ow1#
在调用
configureStore
函数时,应将rootReducer
传递给reducer
选项。authSlice.ts
:字符串
queries.ts
:型
rootReducer.ts
:型
store.ts
个型
App.tsx
:型
控制台日志:
的数据
完整示例:stackblitz