0

我正在尝试在登录减速器中更改我的状态,但在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],
    },
}),

这会在我的控制台中打印以下错误:

图片

4

1 回答 1

0

我自己没有使用过 Redux 的工具包/ createSlice(),但他们有一整节关于异步 thunk:https ://redux-starter-kit.js.org/api/createAsyncThunk

即你是dispatch()异步函数(触发副作用的动作),并且不要在减速器中执行副作用(它们不应该是异步的)。

于 2020-04-29T21:43:42.533 回答