Javascript 外还原剂的火还原作用
首先,我知道(或者我想我已经读过)你不应该从减速器中触发动作。在我的情况下,我使用Javascript 外还原剂的火还原作用,javascript,reactjs,redux,redux-toolkit,redux-oidc,Javascript,Reactjs,Redux,Redux Toolkit,Redux Oidc,首先,我知道(或者我想我已经读过)你不应该从减速器中触发动作。在我的情况下,我使用reduxOIDC来处理针对我的应用程序的身份验证。用户登录后,redux oidc启动redux oidc/user\u FOUND操作,并将用户配置文件设置为state.oidc.user切片 登录后,我需要从我的数据库中查找有关用户的其他信息,这些信息不在OIDC响应中。目前,我正在从redux oidc.CallbackComponent.successCallback启动fetchUserPrefsthu
reduxOIDC
来处理针对我的应用程序的身份验证。用户登录后,redux oidc
启动redux oidc/user\u FOUND
操作,并将用户配置文件设置为state.oidc.user
切片
登录后,我需要从我的数据库中查找有关用户的其他信息,这些信息不在OIDC响应中。目前,我正在从redux oidc.CallbackComponent.successCallback
启动fetchUserPrefs
thunk,它可以正常工作
我的问题是,当用户有一个活动会话并打开一个新浏览器,或者手动刷新页面并再次初始化应用程序时,回调不会命中,因此不会发生额外的用户水合作用。似乎我想做的是添加一个extraReducer
,它侦听redux oidc/USER\u找到的操作并触发thunk,但这将从reducer启动一个操作
有更好的方法吗
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;
您不能从减速器分派操作,这是正确的。您希望侦听要分派的操作,并分派另一个操作作为响应。这是中间件的工作。您的中间件应该如下所示:
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);
};
您可以阅读上的文档了解更多信息。听起来像是定制中间件的工作。