我试图更多地了解高阶组件,我的理解是典型的模式是这样的:
const HOC = (WrappedComponent) => {
...
return class extends React.Component {
render(){
<WrappedComponent {...this.props} />
}
}
}
你可以这样称呼:HOC(CustomComponent)
然而,包括 react-redux 在内的许多流行库都返回一个函数,该函数又返回组件:
const connect = (mapStateToProps) => {
...
const storeToPass = mapStateToProps(store)
return function(WrappedComponent) {
return class extends React.Component {
render(){
<WrappedComponent {...this.props, ...storeToPass} />
}
}
}
}
你会这样称呼它:connect(mapState)(CustomComponent)
我的问题是为什么?这有什么原因吗,或者只是对模式的偏好? 为什么不能为连接功能执行此操作?
const connect = (mapStateToProps, WrappedComponent) => {
...
const storeToPass = mapStateToProps(store)
return class extends React.Component {
render(){
<WrappedComponent {...this.props, ...storeToPass} />
}
}
}
并这样称呼它:Connect(MapState, CustomComponent)
有什么区别吗?
首先,connect
接受(最多(四个参数:mapStateToProps
、mapDispatchToProps
、mergeProps
和options
。 https://react-redux.js.org/api/connect#connect
当然,从理论上讲,函数签名可以翻转为connect(Component, mapStateToProps, mapDispatchToProps, mergeProps, options)
。
但是,文档中给出的原因:
您可以使用 hoc 使不同的组件获得相同的行为
他们的示例给出了两个不同的组件登录/注销操作:
// first call: returns a hoc that you can use to wrap any component
const connectUser = connect(
mapState,
mapDispatch
)
// second call: returns the wrapper component with mergedProps
// you may use the hoc to enable different components to get the same behavior
const ConnectedUserLogin = connectUser(Login)
const ConnectedUserProfile = connectUser(Profile)
https://react-redux.js.org/api/connect#connect-returns
有点晚了,但除了@anthonygood的回答之外,还有另一个原因与使用多个 HOC 有关。请参阅有关 HOC 的反应文档。简而言之,不必将调用链到 HOC,您可以按照下面的代码片段所示编写它们,这些代码片段直接取自 HOC 上的 REACT 文档。
// Instead of doing this...
const EnhancedComponent = withRouter(connect(commentSelector)(WrappedComponent))
// ... you can use a function composition utility
// compose(f, g, h) is the same as (...args) => f(g(h(...args)))
const enhance = compose(
// These are both single-argument HOCs
withRouter,
connect(commentSelector)
)
const EnhancedComponent = enhance(WrappedComponent)
react 中的 HOC 概念是在 redux 库之后引入的。函数本身被称为反应中的组件。所以,你知道这笔交易;更改已经发布的所有内容非常复杂。如果它必须实现 react 钩子的实现方式,那么大多数软件都需要进行错误的更改。
Connect
返回一个函数,因为这个函数需要非常灵活,这反过来意味着它必须将许多自定义选项作为参数。当然,CustomComponent
可能只是传递给Connect
的另一个论点,以便您HOC(CustomComponent, option1, ...optionN)
.
Redux 创建者采取的另一个更整洁的选项是将所有自定义选项作为参数单独传递给 Connect,作为回报,获得另一个已经自定义的功能。然后,此自定义函数将CustomComponent
作为唯一的参数。