我正在尝试在登录减速器中更改我的状态,但在state.user = data.user
操作之后,console.log
打印undefined。
我的授权切片:
import { createSlice } from '@reduxjs/toolkit';
import api from '../../config/api';
const authSlice = createSlice({
name: 'auth',
initialState: {
user: null,
token: '',
},
reducers: {
async register(state, action) {
console.log(action);
await api
.post('users', action.payload)
.then(({ data }) => {
state = data.data;
console.log(state);
})
.catch((err) => {
console.log(err);
});
},
async login(state, action) {
try {
const { data } = await api.post('sessions', action.payload);
console.log(state);
state.user = data.user;
console.log(state);
state.token = data.token;
} catch (err) {
console.log(err.response && err.response.data.error);
}
},
},
});
const { actions, reducer } = authSlice;
export const { register, login } = actions;
export default reducer;
我的店铺:
import {
configureStore,
combineReducers,
getDefaultMiddleware,
} from '@reduxjs/toolkit';
import { AsyncStorage } from 'react-native';
import {
persistReducer,
persistStore,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from 'redux-persist';
import { authReducer, newsReducer } from '../features';
const rootReducer = combineReducers({
authReducer,
newsReducer,
});
const persistConfig = {
key: 'root',
storage: AsyncStorage,
whitelist: ['auth'],
};
const persistReducers = persistReducer(persistConfig, rootReducer);
const store = configureStore({
reducer: persistReducers,
middleware: getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
});
export const persistor = persistStore(store);
export default store;
另外,当我将我的中间件属性从 configureStore 配置为
middleware: getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
这会在我的控制台中打印以下错误: