【问题标题】:HoC component connected to redux arround component connected to reduxHoC 组件连接到 redux arround 组件连接到 redux
【发布时间】:2020-11-01 08:20:29
【问题描述】:

我有基本组件,假设BaseContainer 连接到redux 并有一些方法。现在我想创建几个CustomContainer 组件,它们也应该连接到redux,并且应该可以访问BaseContainer 组件的所有方法和状态。

所以BaseContainer 将是:

class BaseContainer extends React.Component {
   state = {};
   
   method1() {};
   method2() {};
   method3() {};
}
export default connect(mapStateToProps, mapDispatchToProps)(BaseContainer);

CustomContainers 之一应该是:

   class CustomContainer extends BaseContainer {
       // should have access to all imports, methods and props of BaseContainer
    }
    export default connect(mapStateToProps, mapDispatchToProps)(CustomContainer);

试过这个,但似乎继承在 React 中不能很好地工作,也不推荐。 在这里我收到错误Super expression must either be null or a function

尝试使用 HoC 的其他方法:

class CustomContainer extends React.Component {
           // should have access to all imports, methods and props of BaseContainer
        }
        export default connect(mapStateToProps, mapDispatchToProps)(BaseContainer(CustomContainer));

现在我遇到了错误:Unhandled Rejection (TypeError): Object(...) is not a function

出了什么问题,我怎样才能让我的CustomContainer 可以访问BaseContainer 的所有导入、道具和状态?

【问题讨论】:

    标签: reactjs inheritance redux higher-order-components


    【解决方案1】:

    您可能应该阅读 react 文档,特别是 Composition vs. Inheritance。 React 更倾向于组合而不是继承。 BaseContainer 也不是一个高阶组件,而是一个常规组件,它似乎没有返回任何要渲染的东西。

    Higher Order Component

    这是一个我认为可以帮助你接近你所追求的实现

    const withBaseCode = WrappedComponent => {
      class BaseContainer extends Component {
        state = {};
    
        method1 = () => {...}
        method2 = () => {...}
        method3 = () => {...}
    
        render() {
          return (
            <WrappedComponent
              method1={this.method1}
              method2={this.method2}
              method3={this.method3}
              {...this.props}
            />
          );
        }
      }
    
      const mapStateToProps = state => ({...});
      const mapDispatchToProps = {...};
    
      return connect(mapStateToProps, mapDispatchToProps)(BaseContainer);
    };
    

    然后使用它只是一个普通的 HOC,所以给定一些组件

    const CustomContainer = ({ method1, method2, method3, ...props}) => {
      ...
    
      return (
        ...
      );
    };
    
    const CustomContainerWithBaseCode = withBaseCode(CustomContainer);
    

    一些应用容器

    function App() {
      return (
        <div className="App">
          ...
    
          <CustomContainerWithBaseCode />
        </div>
      );
    }
    

    上述代码的演示减去实际上连接到一个redux商店。

    【讨论】:

      猜你喜欢
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      • 2017-12-17
      • 1970-01-01
      • 2021-09-08
      • 2017-04-13
      • 2016-01-02
      相关资源
      最近更新 更多