React只负责UI层,也就是我们通常在MVC框架中 所说的View层,所以在使用React开发中 我们得引入Redux
负责Model
一开始学习Redux的中间层 有点 摸不到头,
其实只要你注意观察,这个所谓的middlerware其实就是一个 责任链
import { applyMiddleware, createStore } from "redux";const reducer = (initialState=0, action) => { if (action.type === "INC") { return initialState + 1; } else if (action.type === "DEC") { return initialState - 1; } else if (action.type === "MULT") { throw new Error("AHHHH!!"); } return initialState;}const logger = (store) => (next) => (action) => { console.log("Logged", action); return next(action);//打印action 然后将调用 next函数 将action对象 交给 责任链上的下一个处理函数};const errorHandler = (store) => (next) => (action) => { try { return next(action);//同上,先try catch 然后把action对象 交给责任链上的下一个处理函数 } catch(e) { console.log("ERROR!", e); }};const middleware = applyMiddleware( logger, errorHandler)const store = createStore(reducer, middleware)store.subscribe(() => { console.log("store changed", store.getState());})store.dispatch({type: "INC"})store.dispatch({type: "INC"})store.dispatch({type: "INC"})store.dispatch({type: "DEC"})store.dispatch({type: "DEC"})store.dispatch({type: "DEC"})store.dispatch({type: "MULT"})store.dispatch({type: "DEC"})
-------------
下面是异步IO的责任链设计
import { applyMiddleware, createStore } from "redux";import axios from "axios";import logger from "redux-logger";import thunk from "redux-thunk";import promise from "redux-promise-middleware";const initialState = { fetching: false, fetched: false, users: [], error: null,};const reducer = (state=initialState, action) => { switch (action.type) { case "FETCH_USERS_PENDING": { return {...state, fetching: true} break; } case "FETCH_USERS_REJECTED": { return {...state, fetching: false, error: action.payload} break; } case "FETCH_USERS_FULFILLED": { return { ...state, fetching: false, fetched: true, users: action.payload, } break; } } return state}const middleware = applyMiddleware(promise(), thunk, logger()) //这里加入了thunk promise() logger() //都是责任链上的某一个环节,promise 负责异步IO 返回的时候 , //再一次重新调用dispatch函数,并修改type类型为 FETCH_USERS_PENDING 等情况 本质上就是在我们的type类型上 根据异步IO返回的结果 再一次添加了PENDING等状态 然后再调用dispatch函数分发action const store = createStore(reducer, middleware)store.dispatch({ type: "FETCH_USERS", payload: axios.get("http://rest.learncode.academy/api/wstern/users")})
reference:
Connecting React & Redux - Redux Tutorial youtube.com
reactjs http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_three_react-redux.html