【问题标题】:Why do we need to export the connect method for it to work?为什么我们需要导出连接方法才能工作?
【发布时间】:2017-10-02 08:21:38
【问题描述】:

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

例子:

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

为什么这会有所不同?

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

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

    所以当你返回 dispatch 返回的组件时,你实际上返回了正确的组件。您传递给 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()} />
                         )
                   }
    
             }
        }
    
    }
    

    【讨论】:

    • 太棒了。这很好地解释了它。
    • 很高兴它帮助了你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-13
    • 2012-11-13
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多