从 extraReducers 触发 redux 动作

fire redux action from extraReducers

首先,我知道(或者我想我已经读过)你永远不应该从 reducers 中触发 action。在我的情况下,我使用 redux-oidc 来处理针对我的应用程序的身份验证。用户登录后,redux-oidc 触发 redux-oidc/USER_FOUND 操作并在 state.oidc.user 切片中设置用户的配置文件。

登录后,我需要从我的数据库中查找不在 OIDC 响应中的有关用户的其他信息。目前,我正在从 redux-oidc.CallbackComponent.successCallback 发射 fetchUserPrefs thunk,它按预期工作。

我的问题是,当用户有一个活动会话并打开一个新浏览器,或手动刷新页面并再次初始化该应用程序时,回调未被触发,因此不会发生额外的用户水合作用。 似乎 我想做的是添加一个 extraReducer 来监听 redux-oidc/USER_FOUND 动作并触发 thunk,但这会从减速机.

有更好的方法吗?

import {createAsyncThunk, createSlice} from '@reduxjs/toolkit';
import { RootState } from '../../app/store';
import {User} from "oidc-client";

export const fetchUserPrefs = createAsyncThunk('user/fetchUserPrefs', async (user: User, thunkAPI) => {
    // the call out to grab user prefs
    // this works as expected when dispatched from the CallbackComponent.successCallback
    return user;
})

function hydrateUserState(state: any, action: any) {
    // set all the state values from the action.payload
    // this works as expected
}

export interface UserState {
    loginId: string;
    firstName: string;
    lastName: string;
    email: string;
    photoUrl: string;
}

const initialState: UserState = {
    loginId: '',
    firstName: '',
    lastName: '',
    email: '',
    photoUrl: '',
};

export const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
    },
    extraReducers: (builder) => {
        builder
            .addCase('redux-oidc/USER_FOUND', fetchUserPrefs) // I want to do this, or something like it
            .addCase(fetchUserPrefs.fulfilled, hydrateUserState)
            .addDefaultCase((state, action) => {})
    }
});

export const selectUser = (state: RootState) => state.user;
export default userSlice.reducer;

你说得对,你不能从 reducer 中分派一个动作。您想要监听要分派的动作并分派另一个动作作为响应。这是中间件的工作。您的中间件应如下所示:

import { USER_FOUND } from 'redux-oidc';
import { fetchUserPrefs } from "./slice";

export const oicdMiddleware = (store) => (next) => (action) => {
  // possibly dispatch an additional action
  if ( action.type === USER_FOUND ) {
    store.dispatch(fetchUserPrefs);
  }
  // let the next middleware dispatch the 'USER_FOUND' action
  return next(action);
};

您可以阅读 custom middleware 上的文档了解更多信息。