如何使用 React 高阶函数最大化可组合性?

How to maximize composability with React higher-order functions?

我指的是this part of the official React tutorial (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()函数?

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

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

你怎么看,它是一个函数 return 另一个函数。

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

const enhance = connect(commentListSelector, commentListActions);

第二次它得到我们在连接函数中return的组件

const ConnectedComment = enhance(CommentList);

但不仅是组件,我们 return 连接我们从 redux 获得的新道具 - 所以它是如何从 redux 获取数据的方法,查看更详细的示例(如果这对你来说还不够,你可以在上面的评论中查看 link):

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 个组件有用。