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了學習

相關文章
相關標籤/搜索