如何在 Immutablejs 和 Redux 以及 Flux 和 React 中设置 Ember 之类的计算属性 [英] How to setup Ember like computed properties in Immutablejs and Redux and Flux and React

查看:19
本文介绍了如何在 Immutablejs 和 Redux 以及 Flux 和 React 中设置 Ember 之类的计算属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于在 Ember 对象模型中计算属性.这是指定依赖于其他属性的计算属性的一种便捷方式.

I am used to computed properties in Ember Object Model. It's a convenient way to specify computed properties that depend on other properties.

fullName 取决于 firstNamelastName,我可以将计算属性设置为函数 computeProperties 并调用computeProperties 每次我进行更改.

Say fullName depends on firstName and lastName, I can setup computed properties as a function computeProperties and call computeProperties each time I make a change.

示例:

function computeFullName(state) {
  const fullName = state.get('firstName') + state.get('lastName');
  const nextState = state.set('fullName', fullName);
  return nextState;
}

function computeProperties(state) {
  const nextState = computeFullName(state);
  return nextState;
}

// store action handler
[handleActionX](state) {

  let nextState = state.set('firstName', 'John');
  nextState = state.set('lastName', 'Doe');

  nextState = computeProperties(nextState);

  return nextState;
}

有没有办法自动设置计算属性,这样我就不必每次都调用额外的函数.在 Redux 或 ImmutableJS 中.

Is there a way to automatically setup computed properties so that I don't have to call extra functions each time. In Redux or in ImmutableJS.

推荐答案

Redux 作者在这里!

Redux author here!

按照 WildService 的建议使用重新选择 是可行的方法.我认为我们不会将它包含在核心中,因为 reselect 可以很好地完成它的工作,而且我们可以将它作为一个单独的库.

Using reselect as suggested by WildService is the way to go. I think we won't include this in core because reselect does its job well and we're fine with it being a separate library.

我想注意几点:

  • 即使使用重新选择,您也不希望在减速器中计算数据.选择器应该作用于减速器管理的状态.换句话说,选择器是您的 Redux 存储状态和您的组件之间的一步——它们不在您的减速器中.您必须保持 Redux 状态的规范化,以便于更新.

  • Even with reselect, you don't want to compute data inside your reducer. Selectors should operate on the state managed by reducers. In other words, selectors are the step between your Redux store state and your components—they are not inside your reducers. It is essential you keep Redux state normalized so it's easy to update.

我们实际上鼓励你定义选择器与相关的reducer一起,这样当你改变状态形状时,你不必改变你的组件——他们会改用选择器.您可以在 Flux 比较的 Redux 文件夹>中看到一个示例

We actually encourage you to define selectors alongside the relevant reducers, so that when you change the state shape, you don't have to change your components—they would be using the selectors instead. You can see an example of this in the Redux folder of Flux Comparison

我们有一个 文档页面介绍重新选择并描述如何使用它计算派生数据.检查一下.

We have a documentation page introducing reselect and describing how to use it for computing derived data. Check it out.

这篇关于如何在 Immutablejs 和 Redux 以及 Flux 和 React 中设置 Ember 之类的计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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