认识redux

200 阅读1分钟

使用

// ReduxStore.js
import {createStore} from 'redux'
const counterReducer = (state = 0, action) => {
    switch (action.type) {
        case 'add':
            return state + 1
        case 'minus':
            return state - 1
        default:
            return state
    }
}
const store = createStore(
  combineReducers({
    counter: counterReducer,
  }),
  applyMiddleware(logger, thunk),
);
export default store
import React, { Component } from "react";
import store from "../store/ReduxStore";
export default class ReduxPage extends Component {
    componentDidMount() {
        //store监听
        store.subscribe(() => {
            this.forceUpdate();
        });
    }
    add = () => {
        //store修改
        store.dispatch({ type: "add" });
    };
    minus = () => {
        //store修改
        store.dispatch({ type: "minus" });
    };
    stayStatic = () => {
        //store修改
        store.dispatch({ type: "others" });
    };
    render() {
        console.log("store", store);
        return (
            <div>
                <h1>ReduxPage</h1>
                <!--store获取-->
                <p>{store.getState()}</p>
                <button onClick={this.add}>add</button>
                <button onClick={this.minus}>minus</button>
                <button onClick={this.stayStatic}>static</button>
            </div>
        );
    }
}

手写版

export function createStore(reducer, enhancer) {
//enhancer长成这个样子:applyMiddleware(logger, thunk)
  if (enhancer) {
    //返回applyMiddleware(logger, thunk)的执行结果 的执行
    //applyMiddleware(logger, thunk)(createStore)(reducer);
    return enhancer(createStore)(reducer);
  }

  let currentState = undefined;
  let currentListeners = [];
  function getState() {
    return currentState;
  }

  function dispatch(action) {
    currentState = reducer(currentState, action);
    currentListeners.map(lis => lis());
    return action;//有什么用?
  }

  function subscribe(listener) {
    currentListeners.push(listener);
  }
  
  //初始化currentState
  dispatch({ type: "xxxx" });
  
  return {
    getState,
    dispatch,
    subscribe,
  };
}

//middlewares:[logger, thunk]
export function applyMiddleware(...middlewares) {

  //applyMiddleware(logger, thunk)(createStore)(reducer)
  return createStore => (...args) => {
  
    //用到了传进来的createStore
    const store = createStore(...args);
    const midAPi = {
      getState: store.getState,
      dispatch: store.dispatch,
    };
    //使logger和thunk中接收到{getState,dispatch}
    //middlewareChain:[dispatch=>action=>{},dispatch=>action=>{}]
    const middlewareChain = middlewares.map(mw => mw(midAPi));
    
    //覆盖dispatch
    const dispatch = compose(...middlewareChain)(store.dispatch);
    
    return {
      ...store,
      dispatch,
    };
  };
}

//fn1=logger的返回结果dispatch=>action=>{}
//fn2=logger的返回结果dispatch=>action=>{}
//最终的返回:(dispatch)=>{
//    return fn2(()=>{
//        return fn1(dispatch) // fn1(dispatch)得到的是action=>{},也是一个dispatch
//    })
//}
function compose(...funcs) {
  const len = funcs.length;
  if (len === 0) {
    return arg => arg;
  } else if (len === 1) {
    return funcs[0];
  } else {
    return funcs.reduce((a, b) => (...args) => b(a(...args)));
  }
}

// MyReduxStore.js
import { createStore, applyMiddleware } from "../redux";

import { counterReducer } from "./counterReducer";

const store = createStore(counterReducer, applyMiddleware(logger, thunk));

function logger({ dispatch,getState }) {
  //dispatch的传入可以看上面
  //action是用户的传入
  return dispatch => action => {
    action.type && console.log(action.type + "执行啦!");
    return dispatch(action);
  };
}

//dispatch接收了两次?
function thunk({ dispatch,getState }) {
  return dispatch => action => {
    if (typeof action === "function") {
      return action(dispatch, getState);
    } else {
      return dispatch(action);
    }
  };
}

export default store;