redux、action与reducer拆分与合并

redux、action与reducer的拆分与合并
redux
一、在redux中所有的数据均储存于store中,store类似于一颗state树,store是只读属性,也就是只能通过store.getState().xx对其中某个熟性进行读取or store.getState()对所有store数据进行读取简单来讲,redux的一个显著特点是一个应用只提供一个store,在redux中所有的state均储存于同一颗对象树中,即为store,store可通过reducer进行创造
redux两大核心即为action与reducer,action用于描述事件,比如用户干了什么。reducer用于根据需求对store树进行数据修改
store中的数据可在任何地方通过store.getState()进行获取,前提是需要import引入store
二、redux生命周期如下view—>action—>store—>reducer—>view
首先,调用store.dispatch(action)——可以在任何地方调用,例如组件、点击事件、异步请求回调中、定时器等。action主要用于描述当前具体发生事件的对象。 其次store调用reducer对store进行修改,reducer通过action的type类型来寻找对应对函数事件来对store树进行数据更改。需要注意的是每一次操作结束后都需要将state返回出去用于对下一次数据修改的参考 为什么每一次都要返回state呢?主要用于如果无法找到对应type类型对操作就将state原封不动返回
三、最后view通过store.subscribe(this.setState({}))进行监听,当store发生变化则从新store.getState()。并渲染
1,num.js(小reducers1)

let date={
 num:20
 } 
export default function age(state=date,action){      
 switch(action.type){            
  case 'numadd':              
  state.num++               
  return state           
  break           
  case 'numcdd':              
  state.num--               
  return state           
  break           
  default:               
  return state   
}}

2,age.js(小reducers2)

let date={
 age:20
 } 
export default function age(state=date,action){      
 switch(action.type){            
  case 'ageadd':              
  state.age++               
  return state           
  break           
  case 'agecdd':              
  state.age--               
  return state           
  break           
  default:               
  return state   
}} 

3,index.js(将所有小reducers合并)

import {combineReducers} from 'redux'
import counter from './counter'
import age from './todos'
export default combineReducers({
    age,counter
})

4,mystore.js(store仓库)

import {createStore} from 'redux'
import reducer from './index'
const store=createStore(reducer)
export default store

5,App.js(react项目对store数据进行引用与修改)

componentDidMount(){
    store.dispatch({
      type:'numadd'
    })
    store.dispatch({
      type:'ageadd'
    })
    console.log(store.getState().age)
  }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值