脚本宝典收集整理的这篇文章主要介绍了8.react-redux中connect的装饰器用法,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
最近在学习react中的数据状态的管理,也就是redux,react-redux 通常我们要使用redux的时候,我们会写一个reducer和一个action,然后使用connect来包裹你的component,如下App.js所示
import React from 'react'
import {render} from 'react-dom'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import action from 'action.js'
class App extends React.Component{
render(){
return <div>hello world</div>
}
}
function mapStateToProps(state){
return state.main
}
function mapDispatchToProps(dispatch){
return bindActionCreators(action,dispatch)
}
export default connect(mapStateToProps,mapDispatchToProps)(App)
这样并没有什么问题。看着connect的用法,有没有觉得很熟悉?典型的wrapper嘛,这里必须拿装饰器来装一波啊,稍微改改:
import React from 'react'
import {render} from 'react-dom'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import action from 'action.js'
@connect(
state=>state.main,
dispatch=>bindActionCreators(action,dispatch)
)
class App extends React.Component{
render(){
return <div>hello</div>
}
}
看这样是不是逼格更高了点,在实际的开发中,可以将connect抽出来单独写一个模块方便调用,减少代码冗余
需要说明的是,这里用了装饰器,需要安装模块babel-plugin-transform-decorators-legacy,然后在babel中配置:
{
"plugins":[
"transform-decorators-legacy"
]
}
以上是脚本宝典为你收集整理的8.react-redux中connect的装饰器用法全部内容,希望文章能够帮你解决8.react-redux中connect的装饰器用法所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。