安装babel-plugin-transform-decorators-legacy
npm i babel-plugin-transform-decorators-legacy --save-dev
在babel中配置:
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }]
]
vscode可以在项目根目录下添加jsconfig.json文件来消除代码警告
{
"compilerOptions": {
"experimentalDecorators": true
}
}
用装饰器改造一下
import React, {PureComponent} from 'react';
import { connect } from "react-redux";
@connect(mapStateToProps, mapDispatchToProps)
class index extends PureComponent {
//...
}
//获取指定state数据
function mapStateToProps(state) {
//return ...
}
//触发action
function mapDispatchToProps(dispatch) {
//return ...
}
export default index;
进一步改造,把connect单独拎出来
import { connect } from "react-redux";
import {bindActionCreators} from 'redux'
export default (action) => {
return connect(
state => state,
dispatch => bindActionCreators(action, dispatch)
)
}
import React, {PureComponent} from 'react';
import * as common from 'src/pages/action/home'
import connect from 'src/pages/action/common'
@connect(common)
class index extends PureComponent {
//...
}
export default index;