我正在使用redux-toolkit
从MSAL获取accessToken,并使用redux-persist
将存储持久化到localStorage中。我在clientlisting页面中获得搜索结果。当我刷新页面时,它工作正常。但几分钟前,它向我抛出错误"Error in function eval in ./node_modules/redux-persist/es/persistReducer.js:144 baseReducer is not a function"(函数eval in ./node_modules/redux-persist/es/persistReducer.js中的错误:144 baseReducer不是一个函数),我不知道我哪里做错了
store.js
import { configureStore } from '@reduxjs/toolkit'
import usersReducer from "./userSlice";
import storage from 'redux-persist/lib/storage';
import { persistReducer, persistStore } from 'redux-persist';
const persistConfig = { key: 'root', storage, }
const persistedReducer = persistReducer(persistConfig, usersReducer)
export const store = configureStore(
{
reducer: {
users: persistedReducer,
}
})
export const persistor = persistStore(store)
userSlice.js
import { useMsal } from "@azure/msal-react";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { loginRequest } from "./authConfig";
import { msalInstance } from "./pages/index";
export const fetchUsersToken = createAsyncThunk(
"users/fetchUsersToken",
async (dispatch, getState) => {
try {
const token = await msalInstance.acquireTokenSilent(dispatch)
.then((data) => data.accessToken)
return token
} catch (error) {
return error.response.data
}
}
);
const usersSlice = createSlice({
name: "users",
initialState: {
users: null,
loading: true
},
reducers: {},
extraReducers(builder) {
builder
.addCase(fetchUsersToken.pending, (state, action) => {
state.loading = true
})
.addCase(fetchUsersToken.fulfilled, (state, action) => {
state.loading = false,
state.users = action.payload
})
.addCase(fetchUsersToken.rejected, (state, action) => {
state.loading = false
});
}
})
export default usersSlice.reducer;
index.js
import React from "react"
import { Provider, useDispatch } from "react-redux";
import {persistor, store} from "../../store";
import Footer from "../Footer"
import { createTheme, ThemeProvider } from "@mui/material/styles"
import { PersistGate } from 'redux-persist/integration/react';
// Global styles and component-specific styles.
//For changing default blue color for mui text-fields
const theme = createTheme({
palette: {
primary: { main: "#000000" },
},
})
const Layout = ({ children }) => (
<div>
<ThemeProvider theme={theme}>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
{children}
<Footer/>
</PersistGate>
</Provider>
</ThemeProvider>
</div>
)
export default Layout
landingPage.js(我在其中调度操作。)
const request = {
...loginRequest,
account: accounts[0]
}
store.dispatch(fetchUsersToken(request))
1条答案
按热度按时间b09cbbtk1#
在将您共享的代码复制/粘贴到一个正在运行的codesandbox中后,我无法重现您描述的错误,但我确实看到了代码中的一些差异,特别是在
userSlice.js
文件中。我看到的主要差异是thunk错误地访问了
thunkAPI
。createAsyncThunk
有效负载创建者 do 接受两个参数,第一个是arg
(* 例如request
对象 *),第二个是thunkAPI
对象。更新thunk以正确地从thunkAPI
对象中解构dispatch
和getState
。我注意到的第二个差异是在
fetchUsersToken.fulfilled
reducer的情况下,在两行之间使用了Comma operator来设置loading
和users
的状态,虽然这实际上没有多大影响,因为每个操作数都独立地改变state
,但为了可读性和维护起见,仍然应该修复。