我正在使用redux-toolkit,并尝试在每次存储更新后将状态保存到本地存储,而不使用任何第三方库。这是因为redux-persist已不再更新,我不知道有什么好的替代品。经过长时间寻找解决方案,我想到了使用createListenerMiddleware
。
import { configureStore, createListenerMiddleware } from "@reduxjs/toolkit";
import counterSlice, { decrement, increment } from "../Slices/counterSlice";
const listenerMiddleware = createListenerMiddleware()
listenerMiddleware.startListening({
actionCreator: increment,
effect: () => (
localStorage.setItem('count', JSON.stringify(store.getState().counter))
)
})
const listenerMiddleware2 = createListenerMiddleware()
listenerMiddleware.startListening({
actionCreator: decrement,
effect: () => (
localStorage.setItem('count', JSON.stringify(store.getState().counter))
)
})
const counterState = JSON.parse(localStorage.getItem('count') || "null")
export const store = configureStore({
preloadedState: {
counter: counterState === null ? { value: 0 } : counterState
},
reducer: {
counter: counterSlice
},
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(listenerMiddleware2.middleware, listenerMiddleware.middleware)
})
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
有人能告诉我这是否是一个好主意,如果不是,有没有其他正确的方法。