Day17. Redux深入

2020-07-17  本文已影响0人  JackLeeVip

如何使用redux-thunk

使用.png

redux-devtools

redux-devtools.png 逻辑或.png
代码配置.png 初始化状态.png

generator

generator.png 返回结果是一个对象.png

redux-saga的使用

saga.png

-redux-saga, 对代码进行分离, 代码写到另外一个地方

补充两个小知识点

问题.png

redux中间件的实现原理及简单实现方式

  1. 第二种做法, 封装一个函数
function dispatchAndLogging() {
  console.log("dispatch前--dispatching action:", action);
  store.dispatch(action);
  console.log("dispatch后--new state:", store.getState());
}

dispatchAndLogging(addAction(10));
dispatchAndLogging(addAction(5));

=>

  1. 函数的基础之上进行优化: 修改原有的dispatch
const next = store.dispatch;
function dispatchAndLogging() {
  console.log("dispatch前--dispatching action:", action);
  next(action);
  console.log("dispatch后--new state:", store.getState());
}
store.dispatch = dispatchAndLogging;

store.dispatch(addAction(10));
store.dispatch(addAction(5));

=>

  1. 将之前的操作进行一个封装
function patchLogging(store) {
  const next = store.dispatch;
  function dispatchAndLogging() {
    console.log("dispatch前--dispatching action:", action);
    next(action);
    console.log("dispatch后--new state:", store.getState());
  }
  store.dispatch = dispatchAndLogging;
}

patchLogging(store);

store.dispatch(addAction(10));
store.dispatch(addAction(5));
  1. 希望中间可以做一些异步的操作, 封装patchThunk的功能
// 封装patchThunk的功能
function patchThunk(store) {
  const next = store.dispatch;

  function dispatchAndThunk(action) {
    if (typeof action === "function") {
      action(store.dispatch, store.getState);
    } else {
      next(action);
    }
  }

  store.dispatch = dispatchANdThunk;
}

patchLogging(store);
patchThunk(store);

function foo(dispatch, getState) {
  console.log(dispatch, getState);
  dispatch(subAction(10));
}

store.dispatch(foo);
  1. 封装applyMiddleware
// 可变参数, 最后会放到数组中
function applyMiddleware(...middlewares) {
 // 不会做修改无所谓 
 //const newMiddleware = [...middlewares];
 middlewares.forEach(middleware => {
    store.dispatch = middleware(store);
  })
}

applyMiddlewares(patchLogging, patchTHunk);

Reducer代码拆分

preValue, item) => {} 称之为reducer
["aaa", "bbb"].reduce((preValue, item) => {}, 0)
reducer.png
// 拆分counterReducer
const initialCounterState = {
  counter: 0
}
function counterReducer(state, action) {
  switch (action.type) {
    CASE add_number:
      return { ...state, counter: state.counter + action.num };
    CASE sub_number:
      return { ...state, counter: state.counter - action.num };

    default:
      return state;
  }
}

// 拆分homeReducer
const initialHomeState = {
  home:
}

const defaultState = {
  counterInfo: null,
 homeInfo: {}
}

function reducer(state = {}, action) {
  return {
    counterInfo: counterReducer(state.counterInfo, action),
    homeInfo: homeReducer(state.homeInfo, action),
  }
}
过程.png

文件结构重构

结构更清晰.png

coderwhy的React核心技术与开发实战课程链接

少年~来做同学呀~.png
上一篇下一篇

猜你喜欢

热点阅读