设置localStorage的值是否有副作用? [英] Is setting value of the localStorage a side effect?

查看:61
本文介绍了设置localStorage的值是否有副作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个React + Redux应用程序,该应用程序必须将商店中的某些值保存到 localStorage .我有一些实用程序功能,可以将值安全地存储到 localStorage .我有一个动作(重击)和减速器.

I'm working on a React+Redux app that must save certain values from the store to localStorage. I have some utility function, that securely store values to localStorage. I have an action (thunk) and reducer.

const wallet = (state = getFromLocalStorage('wallet'), action) => {
  switch(action.type) {
    case 'SET_WALLET':
      setToLocalStorage('wallet', action.payload); // <--- **SIDE EFFECT?**
      retrun action.payload;
    default:
      return state;
  }
}

减速器必须是纯函数. getToLocalStorage 函数调用是否破坏了reducer的纯度?如果是这样,在哪里可以调用此函数?

Reducers must be pure functions. Does the getToLocalStorage function call break the purity of the reducer? And if so, where is the proper place to call this function?

推荐答案

正如其他评论所述:是的,这肯定是副作用.现在,在这种情况下,它可能不会破坏,但是减速器不是正确的选择.

As the other comment stated: yes, it's definitely a side effect. Now, it's probably not going to break anything in this case, but a reducer isn't the right place for that.

更好的解决方案是在商店订阅回调或中间件中执行此操作.或者,甚至更好的是,使用许多商店持久性之一库已经可用.进行大批量存储也可以接受,特别是如果您只想保留少量数据而不是整个存储状态时.

A better solution would be to either do this in a store subscription callback or a middleware. Or, even better, use one of the many store persistence libraries already available. Doing so in a thunk would also be an acceptable option, especially if you just want to persist a small amount of data rather than the entire store state.

这篇关于设置localStorage的值是否有副作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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