我们平时在用react-redux的时候会用到connect去连接组件的state和action,大概长这个样子:
import { connect } from 'react-redux';
class Counter extends Component{}
const mapStateToProps = (state)=>{
return {
counter:state.counter
}
}
const mapDispatchToProps = (dispatch) => {
return{
jia:() =>{
dispatch(jia());
},
jian:() => {
dispatch(jian());
}
}
}
export default connect(mapStateToProps,mapDispatchToProps)(Counter);
其实上边的写法还有很多对应的优化,请参考:https://www.love85g.com/?p=1595
我们用ES7的@装饰器来优化一下:
安装模块:
yarn add babel-plugin-transform-decorators-legacy
根目录下新增.babelrc文件,如果Babel >= 7.x使用:
{
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }],
]
}
旧版的使用:
{
"plugins": ["transform-decorators-legacy"]
}
详细配置参考官网:https://www.npmjs.com/package/babel-plugin-transform-decorators-legacy
然后使用方式如下:
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
@connect(
state => ({counter:state.counter}),
dispatch => bindActionCreators(types,dispatch)
)
class Counter extends Component{}
export default Counter;
还有用的比较多的就是 @withRouter。