前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Taro如何在子组件中使用store

Taro如何在子组件中使用store

原创
作者头像
挥刀北上
发布2022-05-11 14:35:41
9850
发布2022-05-11 14:35:41
举报
文章被收录于专栏:Node.js开发

前面文章我们分别讲了如何创建reducer如何创建store,如何将store导入到入口组件,现在来了解下如何在页面组件中使用store。

第一步:导入conect装饰器函数

第二步:用装饰器装饰目标组件,不局限于页面组件,装饰器函数的参数有两个,都是函数,第一个参数函数是获取对应的reducer将其映射到自定义属性上,方便在当前组件使用,第二个参数是将dispatch方法映射到当前属性方便当前组件使用。

第一个函数的参数为state,这个state对象上包含了所有的reducer,可以使用解构将其导出,第二个函数的参数为dispatch,即store的dispatch方法。

通过上面的步骤,我们将state和dispatch映射到当前组件的props上面,直接调用props上的属性即可。

代码如下:

代码语言:javascript
复制
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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档