首页 > 解决方案 > redux 容器组件的复用性

问题描述

我们的 react 应用使用 react-redux。

我们正在努力使组件可重用。

我们的组件调用其他容器。当前代码的一部分如下。

容器A

export default connect(
 (state) => ({
   aaaa: state.aaaa
 }) 
)(ComponentA);

组分B

import { ComponentA } from "./ComponentA.container"

const ComponentB = ({bbbb}) => {
  <div>
   // somecodes
   <ComponentB props={componentBProps}/>
  <div>
}

容器B

export default connect(
 (state) => ({
   bbbb: state.bbbb
  })
)(ComponentB);

在这种情况下,containerA 和 containerB 依赖于 state.aaaa / state.bbbb。

我们想重用这些组件,但它们依赖于其他状态(如 state.cccc)。

你有任何商品想法如何做到这一点?

我想出的是

  1. 不要从表示逻辑调用容器。containerA由containerB制作,containerB将containerB传递给CompnentB,然后CompnentB实现ComponentA。

如果嵌套级别不是太多,这可以正常工作。但如果它很深,传递道具就会成为一个问题。

  1. 传递应该使用哪个 store 的 flag,容器判断 flag 并选择要使用的 store。

标签: react-redux

解决方案


推荐阅读