標籤:ios lstat .com tutorial init handle mvc架構 view ref
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
redux的中介層 --reactjs學習