redux简单用法&&自定义middleware+分析

import { createStore, applyMiddleware } from 'redux'


//定义一个actions
const visibleGloble = (visible) => {
  return {
    type: 'CHANGE_VISIBLE_STATE',
    visible: visible || 0,
    text: '这是初始数据'
  }
}
//用函数方法创建action对象
let action = visibleGloble(0)

//定义一个方法 reducer
const reducer = (state = [], action) => {
  switch (action.type) {
    case 'CHANGE_VISIBLE_STATE':
      return {
        ...state,
        visible: true,
        text: '这是修改后数据'
      }
    default :
      return state
  }
}

//创建两个自己的中间件 myPathLogMiddleware
const myPathLogMiddleware = store => next => action => {
  console.log('开始dispath', action)
  const result = next(action)
  console.log('结束dispath', store.getState())
  return result
}
const myPathLogMiddleware2 = store => next => action => {
  console.log('开始dispath2', action)
  const result = next(action)
  console.log('结束dispath2', store.getState())
  return result
}

//combineReducer用法
//combineReducer({reducr1,reducer2})

//创建store
// const store = createStore(combineReducer)
const store = createStore(reducer, applyMiddleware(myPathLogMiddleware))

//最后找个地方调用原始的dispatch, dispatch 传入的是action
store.dispatch(action)/*=> let action = visibleGloble(0)*/

redux官方参考:https://www.redux.org.cn/docs/advanced/Middleware.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值