首页 > 解决方案 > 如何使用 React 高阶函数最大化可组合性?

问题描述

我参考了React官方教程的这一部分(Convention: Maximizing Composability)

// connect is a function that returns another function
const enhance = connect(commentListSelector, commentListActions);
// The returned function is a HOC, which returns a component that is connected
// to the Redux store
const ConnectedComment = enhance(CommentList);

我们应该如何实现 connect() 函数?

标签: javascriptreactjscompositionhigher-order-components

解决方案


从概念上讲,HOC 连接是这样的:

function connect(mapStateToProps, mapDispatchToProps) {
  return function (WrappedComponent) {
    return class extends React.Component {
      render() {
        return (
          <WrappedComponent
            {...this.props}
          />
        )
      }
    }
  }
}

你怎么看,它是一个返回另一个函数的函数。

第一次调用 connect 得到 2 个参数

const enhance = connect(commentListSelector, commentListActions);

在第二个它得到我们在连接函数中返回的组件

const ConnectedComment = enhance(CommentList);

但不仅是组件,我们还使用从 redux 获得的新道具返回 connect - 所以这是如何从 redux 获取数据的方法,请查看更详细的示例(如果这对您来说还不够,您可以查看上面评论中的链接):

function connect(mapStateToProps, mapDispatchToProps) {
  return function (WrappedComponent) {
    return class extends React.Component {
      render() {
        return (
          <WrappedComponent
            {...this.props}
            {...mapStateToProps(store.getState(), this.props)}
            {...mapDispatchToProps(store.dispatch, this.props)}
          />
        )
      }
    } 
  } 
}

对我来说更有用和方便的是 react-hook 模式,检查 useSelector 和 useDispatch 方法从 redux 组件获取数据以进行反应。它更简单,连接了遗留方法,并且仅对 Class 组件有用。


推荐阅读