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了

posted @ 2018-09-26 10:18  明明一颗大白菜  阅读(4662)  评论(0编辑  收藏  举报
<-- -->