前面文章我们分别讲了如何创建reducer如何创建store,如何将store导入到入口组件,现在来了解下如何在页面组件中使用store。
第一步:导入conect装饰器函数
第二步:用装饰器装饰目标组件,不局限于页面组件,装饰器函数的参数有两个,都是函数,第一个参数函数是获取对应的reducer将其映射到自定义属性上,方便在当前组件使用,第二个参数是将dispatch方法映射到当前属性方便当前组件使用。
第一个函数的参数为state,这个state对象上包含了所有的reducer,可以使用解构将其导出,第二个函数的参数为dispatch,即store的dispatch方法。
通过上面的步骤,我们将state和dispatch映射到当前组件的props上面,直接调用props上的属性即可。
代码如下:
import { Component } from 'react'
import { connect } from 'react-redux'
import { View, Button, Text } from '@tarojs/components'
import { add, minus, asyncAdd } from '../../actions/counter'
import './index.scss'
@connect(({ counter }) => ({
counter
}), (dispatch) => ({
add () {
dispatch(add())
},
dec () {
dispatch(minus())
},
asyncAdd () {
dispatch(asyncAdd())
}
}))
class Index extends Component {
componentWillReceiveProps (nextProps) {
console.log(this.props, nextProps)
}
componentWillUnmount () { }
componentDidShow () { }
componentDidHide () { }
render () {
return (
<View className='index'>
<Button className='add_btn' onClick={this.props.add}>+</Button>
<Button className='dec_btn' onClick={this.props.dec}>-</Button>
<Button className='dec_btn' onClick={this.props.asyncAdd}>async</Button>
<View><Text>{this.props.counter.num}</Text></View>
<View><Text>Hello, World</Text></View>
</View>
)
}
}
export default Index
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。