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

查看:174
本文介绍了在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 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
})

在创建商店之前,请阅读那些持久化部分:

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天全站免登陆