传统的react-redux写法
Test.js
import React, { Component } from 'react'
import { connetc } from 'react-redux'
import { bindActionCreators } from 'redux'
import action from './action'
class Test extends Compnent{
render(){
return (
<div>hello world</div>
)
}
}
const mapStateToProps = (state) =>{
return state.Test
}
const mapDispatchToProps = (dispatch) =>{
return bindActionCreators(action,dispatch)
}
export default connetc(
mapStateToProps,
mapDispatchToProps
)(Test)
这种写法需要在每个使用redux的页面都写一段connect的操作,可以将这一段封装成装饰器函数来简化
connetc.js
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
export default (mode,action)=>{
return connect(
state=>state[mode],
dispatch=>bindActionCreators(action,dispatch)
)
}
在test.js中只需要调用装饰器函数传入redux模块名和action即可
Test.js
import React, { Component } from 'react'
import connetc from './connect'
import { bindActionCreators } from 'redux'
import action from './action'
@connect('Test',action)
class Test extends Compnent{
render(){
return (
<div>hello world</div>
)
}
}
export default Test
因为装饰器是未来语法,直接使用会报错,需要babel插件babel-plugin-transform-decorators-legacy
来支持
$ yarn add babel-plugin-transform-decorators-legacy -D
安装完成后,在package.json中(creat-reat-app的babel配置在package.json中)添加如下配置
"babel": {
"presets": [
"react-app"
],
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
]
}
配置完毕后,就可以正常使用装饰器了