zoukankan      html  css  js  c++  java
  • react中的hoc和修饰器@connect结合使用

    在学习react-redux的时候,看到了修饰器这个新的属性,这个是es7的提案属性,很方便。于是我用@connect代替了connect(使用的时候需要配置,这里不赘述),省去了很多不必要的代码,但是我的view层和代码逻辑层是分开的,即view+hoc的模式:

    先看封装的connect:

    import {bindActionCreators} from "redux";
    import {connect} from "react-redux";
    import * as paperActions from "../redux/actions/index"
    
    
    export default connect(
        state=>state,
        dispatch=>bindActionCreators(paperActions,dispatch)
    )
    

      在view页面中引用:

    import React, {Component} from "react"
    import connect from './../../containers/index';
    
    @connect
    export default class Test extends Component {
        render() {
            return (
            <div>......</div>
            )
        }
    }
    

      这个时候我们便已经取到了redux的action和state,那我所有的逻辑代码在hoc文件里面:

    import React, {Component} from "react";
    
    
    const getDisplayName = component => component.displayName || component.name || "Component";
    
    const hoc = WrappedComponent => {
        return class extends Component {
            static displayName = `HOC(${getDisplayName(WrappedComponent)})`;
    
            // 构造
            constructor(props) {
                super(props);
            }
    
    
            componentDidMount() {
                console.log(this.props);
            }
    
    
    
            render() {
                const props = {
                    ...this.props,
             
                };
                return <WrappedComponent {...props} />
            }
        }
    };
    
    export default hoc
    

      此时打印出来“this.props”是得不到state和action的,然后我再hoc里面尝试了各种方法,却一直在报错:

    Leading decorators must be attached to a class declaration
    

      很明显,修饰器只能放在类的前面,于是谷歌了许多资料,发现其实hoc就是一个纯函数,可以当修饰器来使用,于是:

    import React, {Component} from "react"
    import connect from './../../containers/index';
    import hoc from "./hoc"
    @connect
    @hoc
    export default class Test extends Component {
        render() {
            return (
            <div>......</div>
            )
        }
    }
    

     在hoc中就可以使用redux里面的actions和state了

  • 相关阅读:
    窗口参数Hello Win32 之疯狂注释版
    返回代码hdu 2054 A==B?
    function类html5游戏开发零基础开发《圣诞老人送礼物》小游戏
    路径工程OpenCV依赖文件路径自动添加方法
    变形测试数据HDU1181:变形课(DFS)
    类参数Hello MFC 之疯狂注释版
    按钮保存ios学习之xcode到处ipa安装包
    clientapivc api TCP&UDP—helloworld
    文件下载Asp.net下载文件的实例
    选择代码在Ubuntu12.04.2上使用Xmonad窗口管理器(续)
  • 原文地址:https://www.cnblogs.com/mmykdbc/p/9705375.html
Copyright © 2011-2022 走看看