假设我们在react中有如下header组件:
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import actions from './actions';
class Header extends PureComponent{
render(){
return (
<div>这是个组件</div>
)
}
}
const mapStateToProps = state => ({
todos:state.todos
})
const mapDispatchToProps = dispatch => ({
setTodos:value=>dispatch(actions.setTodos(value))
})
export default connect(mapStateToProps,mapDispatchToProps)(Header)
我们在写react组件时结合redux要定义mapStateToProps和mapDispatchToProps两个返回对象的纯函数以便交给connect去包裹使用 具体connect使用查看connect
这里我们就可以用装饰器(Decorator)来改写下:
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import actions from './actions';
@connect(
state=>({
todos:state.todos
}),
dispatch=>({
setTodos:value=>dispatch(actions.setTodos(value))
})
)
class Header extends PureComponent{
render(){
return (
<div>这是个组件</div>
)
}
}
export default Header
如此,改造完成,代码看上去也比改造前的干净整洁了
但是由于装饰器的兼容性问题我们需要使用babel来转换
```// 安装babel插件
yarn add @babel/plugin-proposal-decorators
```
修改package.json下的babel
"babel": {
"presets": [
"react-app"
],
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
]
},
最后一步
根目录下新建jsconfig.json解决编辑器报错问题
{
"compilerOptions": {
"experimentalDecorators": true
}
}
然后就可以愉快的coding了