redux中,初步理解state,action , reducer到底怎么串在一起的

  • 作为初级学者的一些想法
    学习redux的时候总感觉查不到最符合心意的帖子,其实我只想先把最基本的逻辑跑通了,知道全局的state在哪里,在组件中怎么dispatch一个action,组建中怎么读取store 的state,需要引入什么文件之类的。

  • 目前了解的内容(代码就是举个例子,写的比较随便)
    1.写anction

export const func1 = data => ({
  type: 'do1',
  data
})

export const func2 = data => ({
  type: 'do2',
  data
})

2.写reducer

const todos = (state ={}, action) => {
  switch (action.type) {
    case 'do1':
      return {
          user: action.data,
      }
    case 'do2':

    default:
      return state
  }
}

export default dos

3.写store (createStore的第二个参数可以写全局的初始化的state,我一开始纠结了特别久到底在哪里可以写初始的公共的state)

import { createStore } from 'redux'
import rootReducer from './reducers'
 const store = createStore(rootReducer,{
    user:"admin",
    icon:"icon"
 })
export default store

4.在组件中运用
开头部分:

关联redux和当前组件
import { connect } from 'react-redux'
引入要用的action
import { func1} from '../../store/actions'

结尾部分

const mapStateToProps = state => {
  return {
    user: state.user
  }
}

const mapDispatchToProps = dispatch => {
  return {
    doing: text => {
      dispatch(func1(text))
    }
  }
} 
export default connect(mapStateToProps,mapDispatchToProps)(Index)

函数触发 reducer
上一段代码中mapStateToProps,mapDispatchToProps就是把store中本组件需要的state,reducer中的执行函数放到this.props中,
此时this.props如下图:

这里写图片描述
你在组件中就可以用了,this.props.doing(“内容”);
然后 this.props.user就等于“内容”;
当然,如果没有mapDispatchToProps,这里写图片描述
就这样用this.props.dispatch(func1(“内容”))也可以的

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值