在 Redux 应用程序中写入 localStorage 的位置? [英] Where to write to localStorage in a Redux app?

查看:27
本文介绍了在 Redux 应用程序中写入 localStorage 的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将状态树的某些部分保存到 localStorage.什么地方适合这样做?减速器还是动作?

I want to persist some parts of my state tree to the localStorage. What is the appropriate place to do so? Reducer or action?

推荐答案

Reducer 永远不是一个合适的地方,因为 reducer 应该是纯粹的并且没有副作用.

Reducer is never an appropriate place to do this because reducers should be pure and have no side effects.

我建议只在订阅者中进行:

I would recommend just doing it in a subscriber:

store.subscribe(() => {
  // persist your state
})

在创建 store 之前,阅读那些持久化的部分:

Before creating the store, read those persisted parts:

const persistedState = // ...
const store = createStore(reducer, persistedState)

如果您使用 combineReducers(),您会注意到尚未收到状态的 reducer 将使用其默认的 state 参数值正常启动".这可能非常方便.

If you use combineReducers() you’ll notice that reducers that haven’t received the state will "boot up" as normal using their default state argument value. This can be pretty handy.

建议您对订阅者进行去抖,以免写入 localStorage 太快,否则会出现性能问题.

It is advisable that you debounce your subscriber so you don’t write to localStorage too fast, or you’ll have performance problems.

最后,您可以创建一个封装它的中间件作为替代方案,但我会从订阅者开始,因为它是一个更简单的解决方案并且可以很好地完成工作.

Finally, you can create a middleware that encapsulates that as an alternative, but I’d start with a subscriber because it’s a simpler solution and does the job well.

这篇关于在 Redux 应用程序中写入 localStorage 的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆