我应该在 Redux 存储中存储函数引用吗? [英] Should I store function references in Redux store?

查看:137
本文介绍了我应该在 Redux 存储中存储函数引用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以惯用的 React/Redux 方式在我的 React/Redux 应用程序中构建键盘快捷键支持.我计划这样做的方法是拥有以下动作创建者和相关动作:

I'm trying to build keyboard shortcut support into my React/Redux app in an idiomatic React/Redux way. The way I am planning to do this is to have the following action creator and associated action:

registerShortcut(keyCode, actionCreatorFuncReference)

然后,reducer 将使用 keyCode 到 actionCreatorFuncReferences 的映射更新 redux 存储中的注册快捷方式对象.然后我的根组件将侦听 keyup 并查看是否有关联的 keyCode 注册,如果有,则通过操作创建者函数引用调度映射的操作.

The reducer would then update a registeredShortcuts object in the redux store with a mapping of keyCodes to actionCreatorFuncReferences. Then my root component would listen for keyup and see if there is an associated keyCode registered and if so, then dispatch the mapped action via the action creator function reference.

然而,这将是我第一次在我的 Redux 存储中存储函数引用.迄今为止,我只有带有普通值(字符串、整数等)的键的对象.

However, this would be the first time I am storing function references in my Redux store. To date I've only had objects with keys with vanilla values (strings, ints, etc).

Redux 文档说您应该尽最大努力保持状态可序列化.不要在其中放入任何您无法轻松转换为 JSON 的内容.".这是否表明将这样的函数引用存储在我的 Redux 存储中是一个坏主意?如果是这样,有什么更好的方法来完成我在 React/Redux 中尝试做的事情?

The Redux docs says "You should do your best to keep the state serializable. Don’t put anything inside it that you can’t easily turn into JSON.". Does this suggest it's a bad idea to store such function references in my Redux store? If so, what is a better way to accomplish what I'm trying to do in React/Redux?

另一种方法是将 keyCode 和函数引用的映射存储在根 React 组件本身中,但这感觉不太像 Redux,因为现在应用程序状态不在 Redux 存储中.

An alternative approach is just to store the mapping of keyCodes and function references in the root react component itself, but that didn't feel very Redux-like since now application state is not in the Redux store.

推荐答案

不,您不应该在 redux 存储中存储函数引用.它们不可序列化,正如您提到的,状态应该始终可序列化.我能想到的对 redux 最友好的方法就是将热键映射到它们的 actionCreatorFuncNames.

No, you should not store function references in the redux store. They are not serializable, and as you mentioned state should be serializable at all time. The most redux friendly approach I can think of is just to keep the map of hotkeys to their actionCreatorFuncNames.

这篇关于我应该在 Redux 存储中存储函数引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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