在我的状态树中,我有从状态 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/