我可以使用'react-redux''connect'HOC通过mapStateToProps为'通用'React组件提供自定义选择器吗?

时间:2019-02-06 11:49:19

标签: javascript reactjs redux code-reuse

我正在尝试为我的团队正在从事的大型React项目创建可重用的React组件。例如,我有一个面板,其中包含两个子组件,每个子组件都包含其他子组件。

对于我来说,连接到Redux商店的最佳位置是在顶层,并将道具传递到子组件和子子组件(我知道这在一定程度上破坏了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组件?感谢您提供任何见解!

1 个答案:

答案 0 :(得分:1)

这种方法没有错,像connect这样的HOC旨在具有这种好处。

要有效地使用此功能,您必须确定GenericPanelComponent需要哪些道具,并使用connect函数提供它们。我要在当前实现中指出的唯一一件事是,GenericPanelComponent不需要知道它是哪种Panel,因此在完成操​​作时它应该没有其他道具

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

相反,数据应该通过一个道具来传递

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