从不同的切片调用reducer Redux Toolkit

Jam*_*mie 7 typescript reactjs redux redux-toolkit

我有一个authSlice

const authSlice = createSlice({
  name: 'authStore',
  initialState,
  reducers: {
    logout(state = initialState) {
      return { ...state, isAuthenticated: false };
    },
  },
  extraReducers: (builder) => {
    builder.addCase(login.fulfilled, (state, { payload }) => {
      state.isAuthenticated = true;
      localStorage.setItem('userId', payload.userId);
    });

    builder.addCase(login.pending, (state) => {
      state.isLoading = true;
    });

    builder.addCase(login.rejected, (state, { payload, error }) => {
      if (payload) {
        state.loginError = payload;
        state.isLoading = false;
      } else {
        state.loginError = error;
      }
    });
  },
});
Run Code Online (Sandbox Code Playgroud)

和一个userSlice

const userSlice = createSlice({
  name: 'userStore',
  initialState,

  reducers: {
    clearUser(state = initialState) {
      return { ...state };
    },
  },

  extraReducers: (builder) => {
    builder.addCase(getUser.fulfilled, (state, { payload }) => {
      state.user = payload;
      state.isLoading = false;
    });

    builder.addCase(getUser.pending, (state) => {
      state.isLoading = true;
    });

    builder.addCase(getUser.rejected, (state) => {
      state.isLoading = false;
    });
  },
});
Run Code Online (Sandbox Code Playgroud)

我对我的代码有几个问题:

  1. 我如何从拨打clearUser()电话?userSliceauthSlice
  2. 这是好的做法还是反模式?
  3. 如果它是一种反模式,那么在保持 theauthSlice和 the分离的同时执行此操作的替代方法是什么userSlice

Jam*_*mie 2

我最终结合使用了 Zachary 的答案和引用的 SO帖子

为了拥有一个logout通过一次调用即可清除所有状态的函数,我需要创建一个rootReducer包含清除状态逻辑的函数:

import { AnyAction, combineReducers, Reducer } from '@reduxjs/toolkit';
import auth from './auth/authSlice';
import user from './user/userSlice';

const combinedReducer = combineReducers({
  auth,
  user,
});

export const rootReducer: Reducer = (state: RootState, action: AnyAction) => {
  if (action.type === 'authStore/logout') {
    localStorage.clear();
    state = {} as RootState;
  }
  return combinedReducer(state, action);
};

export type RootState = ReturnType<typeof combinedReducer>;
Run Code Online (Sandbox Code Playgroud)

然后authSlice我创建了一个空的logout()减速器:

const authSlice = createSlice({
  name: 'authStore',
  initialState,
  reducers: {
    logout: (state) => {
      /* declared here, handled in the root reducer: ../rootReducer.ts */
    },
  }
})
Run Code Online (Sandbox Code Playgroud)

这最终在我的组件中被消耗,如下所示:

import React from 'react';
import { useDispatch } from 'react-redux';
import { logout } from '../store/auth/authSlice';

export const Home = () => {
  const dispatch = useDispatch();
  return <button onClick={() => dispatch(logout())}>Logout</button>;
};

Run Code Online (Sandbox Code Playgroud)

如果我需要在注销过程中执行任何异步操作,我必须使用类似于 Zachary 在我的 rootReducer 中描述的方法(使用 Thunk)。