redux 重用基于类的组件来分派不同的操作

yws3nbqq  于 2023-03-08  发布在  其他
关注(0)|答案(1)|浏览(123)

我有一个基于类的组件连接到redux。我正在从这个组件中分派一个操作(updateDownloadCount)。这个组件呈现了一些用户界面,有内部状态和一些函数。

class MyComponent extends Component {
  ...
}

const mapDispatchToProps = (dispatch) => {
  return {
    updateDownloadCount: (id) => {
      ...
    }
  }
}

export default connect(null, mapDispatchToProps)(MyComponent);

现在我想在其他地方重用这个组件。除了操作之外,其他一切都应该保持不变。我想分派不同的操作(updateUploadCount)。
我可以传递一些其他的 prop 来区分,然后发送不同的动作,但这似乎没有很好的伸缩性。有没有其他的方法我可以重用该组件。

yfjy0ee7

yfjy0ee71#

可以将零部件的“表示”部分提取到单独的文件中,然后多次使用它。
例如

// MyComponentUI.js
class MyComponentUI extends Component {
  ...
  // use this.props.updateCount (notice more generic name)
}

export default MyComponentUI

用法

// UploadComponent.js
import MyComponentUI from "components/MyComponentUI.js"

const mapDispatchToProps = (dispatch) => {
  return {
    updateCount: (id) => {
       // dispatch updateUploadCount
    }
  }
}

export default connect(null, mapDispatchToProps)(MyComponentUI)

以及

// DownloadComponent.js
import MyComponentUI from "components/MyComponentUI.js"

const mapDispatchToProps = (dispatch) => {
  return {
    updateCount: (id) => {
       // dispatch updateDownloadCount
    }
  }
}

export default connect(null, mapDispatchToProps)(MyComponentUI)

有了这种方法,你甚至可以在Redux提供者之外使用表示组件,例如在故事书或测试中。

相关问题