【问题标题】:Can I use the 'react-redux' 'connect' HOC to provide custom selectors to 'generic' React components through mapStateToProps?我可以使用“react-redux”“连接”HOC 通过 mapStateToProps 为“通用”React 组件提供自定义选择器吗?
【发布时间】:2019-02-06 11:49:19
【问题描述】:

我正在尝试为我的团队正在进行的大型 React 项目创建可重用的 React 组件。例如,我有一个面板,它由两个子组件组成,每个子组件都由进一步的子组件组成。

我连接到 Redux 商店的最佳位置是在顶层并将 props 向下传递给 sub 和 sub-sub 组件(我知道这在一定程度上违背了 Redux 的目的,但否则整个事情变得过于复杂)。

我的问题是如何为这个通用顶级组件的每个“实例”提供不同的选择器,以便将不同的数据提供给它们。我想出的解决方案是将每个“实例”包装在另一个组件中,该组件实际上只包括将“通用”组件包装在 HOC 的“连接”函数中并通过mapStateToProps 传递自定义选择器。

也就是说,我有“通用组件”

// GenericPanelComponent.js
class GenericPanelComponent extends React.Component {
...
// component code
}
export default GenericPanelComponent

那么每个“实例”都会通过“连接”提供不同的数据

// SpecificInstance1.js 
import { connect } from 'react-redux';
import GenericPanelComponent from './GenericPanelComponent';


class SpecificInstance1 extends React.component {
// no code
}
const mapStateToProps = (state) => ({ specificInstanceData: specificInstance1Selector(state) });
export default connect(mapStateToProps)(GenericPanelComponent);

 // SpecificInstance2.js 
    import { connect } from 'react-redux';
    import GenericPanelComponent from './GenericPanelComponent';

 // SpecificInstance2.js 
    class SpecificInstance2 extends React.component {
    // no code
    }
    const mapStateToProps = (state) => ({ specificInstanceData: specificInstance2Selector(state) });
    export default connect(mapStateToProps)(GenericPanelComponent);

这种方法在概念上或架构上是否有任何问题?如果是这样,如何将自定义 Redux 选择器和数据提供给可重用的 React 组件?感谢您提供任何见解!

【问题讨论】:

    标签: javascript reactjs redux code-reuse


    【解决方案1】:

    这种方法没有任何问题,像 connect 这样的 HOC 就是为了具有这种好处而设计的。

    要有效地使用它,您必须弄清楚您的 GenericPanelComponent 需要什么道具,并使用 connect 函数提供它们。在您当前的实现中,我唯一要指出的是 GenericPanelComponent 不需要知道它是哪种类型的面板,因此它不应该像您所做的那样具有不同的道具

    const mapStateToProps = (state) => ({ specificInstance1Data: specificInstance1Selector(state) });
    const mapStateToProps = (state) => ({ specificInstance2Data: specificInstance2Selector(state) });
    

    相反,数据应该来自一个道具

    const mapStateToProps = (state) => ({ specificInstanceData: specificInstance1Selector(state) });
    const mapStateToProps = (state) => ({ specificInstanceData: specificInstance2Selector(state) });
    

    【讨论】:

    • 谢谢——你说得对!我会在上面的代码中更正它...
    • 我什至需要在“实例”组件中有空白代码吗?我可以从“实例”组件中导出连接的通用组件吗? const mapStateToProps = (state) => ({ specificInstanceData: specificInstance2Selector(state) }); export default connect(mapStateToProps)(GenericPanelComponent);
    • 可以,不需要实例组件
    猜你喜欢
    • 1970-01-01
    • 2017-04-13
    • 2018-09-14
    • 2020-08-22
    • 1970-01-01
    • 2021-04-18
    • 2014-06-07
    • 1970-01-01
    • 2019-01-15
    相关资源
    最近更新 更多