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

查看:79
本文介绍了关于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天全站免登陆