Redux Toolkit 将状态保存到本地存储[关闭]

2023-11-21

我正在使用 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

有人可以告诉我这是否是一个好主意,如果不是,是否还有其他正确的方法。


您的方向是正确的,但有一些变化:

访问状态

而不是使用store直接调用变量getState(),您应该访问getState()来自参数的函数effect打回来。

effect: (action: Action, listenerApi: ListenerApi) => void | Promise<void>

Your effect使用两个参数调用函数:action触发了效果并且listenerApi对象,它使您可以访问getState() and 许多其他实用程序.

侦听器中间件不知道存储的 TypeScript 类型,因此您需要以某种方式使其知道。一种方法是使用内联as的断言listenerApi.getState() call.

listenerMiddleware.startListening({
  actionCreator: increment,
  effect: (action, listenerApi) =>
    localStorage.setItem("count", JSON.stringify((listenerApi.getState() as RootState).counter))
});

您还可以按照TypeScript 用法文档部分并使用TypedStartListening实用类型。

处理多个动作

您不需要多个侦听器中间件实例,因为您可以将多个侦听器附加到同一中间件。简单的调用startListening同一件事上多次listenerMiddleware多变的。

然而在这种情况下,一个startListening只需致电即可!你们的两个案例已经有相同的effect打回来。但我们需要能够匹配两者increment and decrement行动。有几种不同的方式侦听器可以检测到匹配的操作。而不是使用actionCreator,它只能匹配一个动作,我们将使用matcher财产。我们在以下的帮助下创建了一个匹配器函数isAnyOf utility.

我们最终的中间件如下所示:

import { createListenerMiddleware, isAnyOf } from "@reduxjs/toolkit";
import { decrement, increment } from "./slice";
import type { RootState } from "./index";

export const listenerMiddleware = createListenerMiddleware();
listenerMiddleware.startListening({
  matcher: isAnyOf(increment, decrement),
  effect: (action, listenerApi) =>
    localStorage.setItem(
      "count",
      JSON.stringify((listenerApi.getState() as RootState).counter)
    )
});

完整的 CodeSandbox 演示

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Redux Toolkit 将状态保存到本地存储[关闭] 的相关文章

随机推荐