小编典典

为什么我们需要导出connect方法才能起作用?

reactjs

如果我尝试连接组件而不直接导出,它将无法连接。

例:

connect(mapstatetoprops, mapdispatchtoprops)(Componentx);
export default Componentx;

为什么这会有什么不同?


阅读 293

收藏
2020-07-22

共1个答案

小编典典

connect对原始组件没有任何作用,而是由高阶组件模式实现的:因此它以React组件为参数,并通过执行需要执行的操作返回另一个组件,例如提供动作创建者和国家作为道具。

因此,当您返回分派返回的组件时,实际上会返回正确的组件。您传递给的组件connect没有redux state and action creators可用的组件。

因此,您可以想到将connect编写为类似

const connect = (mapStateToProps, mapDispatchToProps) => {
    return (WrappedComponent) => {
         return class App extends React.Component {
               {/* some lifecycle optimizations here */}
               render() {

                    return (
                          <WrappedComponent {...this.props} {...mapStateToProps()} {...mapDispatchToProps()} />
                     )
               }

         }
    }

}
2020-07-22