React react-redux 使用装饰器优化 connect代码

1.使用的是React官方提供的脚手架,要先执行 npm run eject 弹出个性化配置;

2.安装插件 npm install babel-plugin-transform-decorators-legacy --save-dev

3.Package.json babel 加上 plugins 配置;

"babel": {
 "presets": [
   "react-app"
 ],
 "plugins": [ ["@babel/plugin-proposal-decorators", { "legacy": true }]]
},

4.配置,修饰器要写在类上面

// 数据
const mapStateToProps = (state) => {
    return {num: state};
} 

// 方法
const actionCreators = { addGun, removeGun, addGunAsync};

// App = connect(mapStateToProps, actionCreators)(App);

@connect(mapStateToProps, actionCreators)
class App extends React.Component {
    render() {
        return(
            <div>
                <h1>现在有{this.props.num}把机枪</h1>
                <button onClick={this.props.addGun}> 申请武器 </button>
                <button onClick={this.props.removeGun}> 撤销武器 </button>
                <button onClick={this.props.addGunAsync}>2s交付</button>
            </div>
        )
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41111068/article/details/86528087