Redux持久化类型错误:store.dispatch不是一个函数

rsaldnfx  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(222)

在学习教程的时候,我得到了这个store.dispatch不是函数错误。我已经搜索了stackoverflow一段时间,但是似乎找不到任何错误。我遗漏了什么?
显示错误[1]的图像:https://i.stack.imgur.com/AekWH.png

import {configureStore, combineReducers} from '@reduxjs/toolkit'
import cartReducer from './cartRedux'
import userReducer from './userRedux'
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from 'redux-persist'
import storage from 'redux-persist/lib/storage'

const persistConfig = {
  key: 'root',
  version: 1,
  storage,
}

const rootReducer = combineReducers({user: userReducer, cart: cartReducer})
const persistedReducer = persistReducer(persistConfig, rootReducer)

export const store = () => configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
})

export const persistor = persistStore(store)

索引

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from 'react-redux'
import {store, persistor} from './redux/store'
import { PersistGate } from 'redux-persist/integration/react'

ReactDOM.render(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>,
  document.getElementById('root')
);
ih99xse1

ih99xse11#

看起来您将store声明为返回已配置存储的函数。

export const store = () => configureStore({ // <-- a function
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
})

然后传递一个对store函数persistStore的引用

export const persistor = persistStore(store) // <-- store not invoked

虽然你 * 可以 * 在每个地方调用store函数,但这并不好,因为你实际上会在应用的不同部分创建多个商店示例,这些示例不会一起工作。你应该只导出和使用一个已经配置好的商店对象。

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
});

export const persistor = persistStore(store);

相关问题