Javascript React Redux Connect直接返回函数而不是组件有什么原因吗?
我试图更多地了解高阶组件,我的理解是典型的模式如下:Javascript React Redux Connect直接返回函数而不是组件有什么原因吗?,javascript,reactjs,redux,react-redux,higher-order-components,Javascript,Reactjs,Redux,React Redux,Higher Order Components,我试图更多地了解高阶组件,我的理解是典型的模式如下: const HOC = (WrappedComponent) => { ... return class extends React.Component { render(){ <WrappedComponent {...this.props} /> } } } 您可以这样调用它:connect(mapState)(CustomComponen
const HOC = (WrappedComponent) => {
...
return class extends React.Component {
render(){
<WrappedComponent {...this.props} />
}
}
}
您可以这样调用它:connect(mapState)(CustomComponent)
我的问题是为什么?这有什么原因吗?或者这只是一种模式偏好?为什么不能为连接功能执行此操作
const connect = (mapStateToProps, WrappedComponent) => {
...
const storeToPass = mapStateToProps(store)
return class extends React.Component {
render(){
<WrappedComponent {...this.props, ...storeToPass} />
}
}
}
const connect=(mapStateToProps,WrappedComponent)=>{
...
const storeToPass=mapStateToProps(存储)
返回类扩展了React.Component{
render(){
}
}
}
并这样称呼它:Connect(MapState,CustomComponent)
有什么不同吗?react中的HOC概念是在redux库之后引入的。函数本身被称为react中的一个组件。所以,你知道交易;更改已经发布的所有内容是相当复杂的。如果它必须实现react hook的实现方式,那么大多数软件都需要进行错误的更改。首先,
connect
接受(最多)四个参数:MapStateTrops
,mapDispatchToProps
,mergeProps
和选项
当然,从理论上讲,函数签名可以被翻转到连接(组件、mapStateToProps、mapDispatchToProps、mergeProps、选项)
但是,文件中给出的理由如下:
您可以使用hoc使不同的组件获得相同的行为
他们的示例给出了两个不同的组件登录/注销操作:
//第一个调用:返回可用于包装任何组件的hoc
const connectUser=connect(
mapState,
地图发送
)
//第二个调用:返回带有mergedProps的包装器组件
//您可以使用hoc使不同的组件获得相同的行为
const ConnectedUserLogin=connectUser(登录)
const ConnectedUserProfile=连接用户(配置文件)
Connect
返回一个函数,因为该函数需要非常灵活,这意味着它必须将许多自定义选项作为参数。当然CustomComponent
可能只是传递给Connect
的另一个参数,这样您就可以拥有HOC(CustomComponent,option1,…optionN)
Redux创建者采用的另一个更简洁的选项是将所有自定义选项作为参数传递,以单独连接,作为回报,获得另一个已经自定义的函数。然后,此自定义函数将
CustomComponent
作为唯一参数 有点晚了,但除了@anthonygood的答案外,还有另一个原因与使用多个HOC有关。请参阅HOCs上的react文档。简单地说,不必将调用链接到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)
除了更容易部分应用外,我不认为第一种方法比第二种方法有任何其他优势。很好的解释,正是我想要的。谢谢
// 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)