react中的hoc和修饰器@connect结合使用

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

先看封装的connect:java

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页面中引用:react

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文件里面:redux

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里面尝试了各类方法,却一直在报错:app

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了学习

相关文章
相关标签/搜索