本文介绍了为什么我们需要导出 connect 方法才能工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试连接组件而不直接导出,则连接失败.

If i try to connect a component without exporting directly it fails to connect.

示例:

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

为什么这会有什么不同?

Why should this make any difference?

推荐答案

connect 不对原始组件做任何事情,而是High Order Component 模式:因此它将一个 React 组件作为参数并通过执行操作返回另一个组件它需要像提供动作创建者和状态作为道具一样.

connect doesn't do anything to the original component, rather it is the implementation of the High Order Component pattern: so it that takes a React component as an argument and returns another component by the performing the actions it need to do like providing the action creators and the state as props.

所以当你返回dispatch返回的组件时,实际上返回的是正确的组件.您传递给 connect 的组件没有可用的 redux state 和 action creators.

So when you return the component returned by dispatch, you actually return the correct component. The component that you pass to connect doesn't have the redux state and action creators available to it.

所以你可以把连接写成这样的东西

So you could think of connect to be written somthing like

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

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

         }
    }

}

这篇关于为什么我们需要导出 connect 方法才能工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 19:10