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