对 redux 存储中的数据进行可重用计算的最佳实践 [英] Best practice for reusable calculations on data in redux store

查看:16
本文介绍了对 redux 存储中的数据进行可重用计算的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚完成了一个 redux 应用程序的连接,到目前为止它很棒.但是,由于状态存储在一个巨大的存储中,因此您没有任何模型可以从中访问数据.

I've just finished wiring up a redux app, and it's fantastic so far. However, because state is stored in a giant store, you don't have any models that you're accessing your data from.

假设我有一个模型类,用于存储有关用户的一些信息.我通常会向名为 display_name 的类添加一个函数,该函数巧妙地组合了它们名称的不同部分.有了这个,我的不同视图可以简单地调用 display_name 而不是他们需要知道如何自己计算它.

Let's say I have a model class that stores some information about a user. I'd usually add a function to the class called display_name that combines the different parts of their name intelligently. With that, my different views could simply call display_name instead of them needing to know how to calculate it themselves.

Redux 明确表示不要在状态中存储计算值,因此将其保留在组件中进行定义.但这不可能是正确的,因为那样您最终会在需要它的每个组件中复制此代码.

Redux explicitly says not to store calculated values in the state, so that leaves it to being defined in the components. This can't possibly be right though, because then you'd end up duplicating this code in every component that needs it.

存储这个逻辑的合适位置在哪里?

Where is the proper place to store this logic?

推荐答案

最简单的方法是创建实用函数来计算这些数据,并将它们放在一个单独的模块中,该模块可由许多组件的 mapStateToProps 函数使用.一个超级简单的例子:

The simplest method is to create utility functions to calculate this data and put them in a separate module that can be used by many components' mapStateToProps functions. A super-simple example:

import { displayName } from "./utils";

function mapStateToProps(state) {
  return {
    displayName: displayName(state.user)
  };
}

function MyComponent(props) {
  return <div>Name: {props.displayName}</div>;
}

export default connect(mapStateToProps)(MyComponent);

这篇关于对 redux 存储中的数据进行可重用计算的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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