javascript - 尽管异步计算,Redux 最小状态?

标签 javascript reactjs asynchronous redux state

在我的状态树中,我有从状态 A 派生的数据 B

B 可以是图片、3D 几何图形、音乐轨道等,并且它基于参数A 中已有的计算状态树。 但关键是 B 是从 A 异步计算的。

每当 A 发生变化时,

B 也会发生变化。 B 可能是也可能不是可序列化的。

建议将 redux 状态保持在最低限度,我尝试使用选择器来实现此目的并从状态中删除 B 。但是,由于 B 是异步计算的,因此看起来我无法使用选择器或内存选择器(例如 reselect)。是否有任何解决方案可以让状态保持最小且不包含 B

最佳答案

你的 redux 存储有多少个 reducer ?您是否使用combinereducers()来管理多个reducer?如果是这样,A和B都可以是单独的reducer,具有自己的初始状态,并且与您的React组件具有自己的本地状态,并从相应的生命周期事件方法分派(dispatch)异步操作创建器来更新 Prop

如果从 A 传递给 B 的那些 props 仅源自其父组件,不需要存储在 reducer 的初始状态上,则可以使用 propTypes & defaultProps 。它允许您为组件分配 Prop 名称的 Prop 类型,而无需将它们放入 reducer 中。

例如这里是react bootstrap的源代码 您将看到如何设置需要传递给其组件的默认 Prop 。当组件有自己的 proptype 和 defaultprop 设置时,您不需要从 redux 存储传递这些 props。您可以从组件 A 动态生成 prop 值并将其传递给 B。

import classNames from 'classnames';
import React from 'react';
import elementType from 'react-prop-types/lib/elementType';

import { bsClass, prefix, splitBsProps } from './utils/bootstrapUtils';

const propTypes = {
  /**
   * Turn any fixed-width grid layout into a full-width layout by this property.
   *
   * Adds `container-fluid` class.
   */
  fluid: React.PropTypes.bool,
  /**
   * You can use a custom element for this component
   */
  componentClass: elementType,
};

const defaultProps = {
  componentClass: 'div',
  fluid: false,
};

class Grid extends React.Component {
  render() {
    const { fluid, componentClass: Component, className, ...props } =
      this.props;
    const [bsProps, elementProps] = splitBsProps(props);

    const classes = prefix(bsProps, fluid && 'fluid');

    return (
      <Component
        {...elementProps}
        className={classNames(className, classes)}
      />
    );
  }
}

Grid.propTypes = propTypes;
Grid.defaultProps = defaultProps;

export default bsClass('container', Grid);

关于javascript - 尽管异步计算,Redux 最小状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42280389/

相关文章:

javascript - angular-google-maps 中的标记与标记指令

javascript - 将图像从屏幕中间移动到滚动的 Angular 落

reactjs - 替换 Query 对象的 my 字段时缓存数据可能会丢失

javascript - 如何从异步调用返回响应?

javascript - 奇怪的div高度错误: webkit or jQuery bug?

javascript - 在 Jquery 中命名和嵌入函数

javascript - "Can only update a mounted or mounting component "componentDidMount 中的警告

javascript - Api请求在swagger和postman中工作但在js中不起作用(使用axios)

javascript - 如何创建并依赖异步 JavaScript 模块?

c# - Haskell 相当于 C# 5 async/await