React--Redux工作流程及react-redux


本文參考自https://www.cnblogs.com/goodjobluo/p/9077010.html

Redux工作流程

Redux工作流程

Redux三大基本原則

  1. 單一事件原則:所有狀態和數據都保存在store中,且只存在一個store
  2. 狀態只讀原則:state數據是只讀的,不能直接修改,只能通過派發動作進行處理
  3. 使用純函數處理:返回值只和傳入的參數有關

Action

const add = () => {
   return {
      type : ADD,
      data: 1
   }
}

以上定義了一個名為add的action,type為reducer識別處理的標識,data為傳入的數據

reducer

const reducer = (state, action) => {
   switch(action.type){
      case 'ADD':
         state['sum'] = action.data
         return [...state]
         break
      ...
   }
}

以上根據action類型,對state進行處理並返回

store

import {createStore} from 'redux'
let store = createStore(reducer)

以上就創建出了store,store有三個方法:
store.getState() :獲取state
store.dispatch(action):派發action
store.subscribe(listener):監聽store中數據更新

react-redux

容器組件與傻瓜組件

傻瓜組件僅僅根據父組件傳入props渲染數據,容器組件有自己的state,並可以獲取store中數據,可以派發action來更改store中的數據

通過connect函數將傻瓜組件轉為容器組件,並傳入函數參數實現監聽store數據更改

connect(mapStateToProps, mapDispatchToProps , mergeProps , options )()
第一個參數為store數據與組件中數據的對應方式,后面幾個參數通常省略。返回函數中傳入傻瓜組件

class appComponent extends React.component{
      ...
}
mapStateToProps = (state) => {
   return {
      // 本組件中的newItem數據對應state中的newState
      newItem: state.newItem
   }
}
connect(mapStateToProps)(appComponent)

異步中間件

通常情況下,我們需要派發異步action,如發送ajax請求。所以在action發給reducer處理之前,需要通過中間件處理
以下介紹redux-promise-middleWare的使用

//Store.js 加載中間件
import { applyMiddleware,createStore } from 'redux';
import createPromiseMiddleware from 'redux-promise-middleware';
import reducer from './reducers/index';

const store = createStore({//createStore 可以接受應用初始狀態作為參數,這時, `applyMiddleware` 就是第三個參數。
	reduer,
	applyMiddleware([createPromiseMiddleware()])
});
export default store;

發起異步action#

//actions.js
export const getTodos = () => {
  const apiUrl = `/todos`;
  return {
    type: GET_TODO,
    //屬性 payload 值為 Promise 類型(中間件據此判斷是否需要異步處理)
    payload: fetch(apiUrl).then(response => {
      if (!response.ok) {
        //請求返回的可能是500等錯誤,也會執行到這里,需將狀態設置為 rejected
        return Promise.reject(response.status);
      }
      return response.json();
    })
  };
}

處理異步 actions#
一般 action 的處理,發起和處理是一一對應的,而異步 action 則有三個 action 來處理,分別對應異步的三種狀態

${GET_TODO}_PENDING 異步請求執行后會立刻 dispatch 此 action,表示請求已發出,正在等待返回值

${GET_TODO}_FULFILLED 異步請求成功后會 dispatch 此 action,注意 Response 只要回來,即使是 500,也會執行到這里

${GET_TODO}_REJECTED 異步請求失敗后會 dispatch 此 action

上述三個 action 及后綴皆為中間件redux-promise-middleware的約定,不同中間件約定可能不一致。

//reducer.js
case `${GET_TODO}_PENDING`: {
  return {
    status: FetchStatus.LOADING,
  }
}

case `${GET_TODO}_FULFILLED`: {
  return {status: FetchStatus.SUCCESS, items: action.payload};
}

case `${GET_TODO}_REJECTED`: {
  return {status: FetchStatus.FAILURE, error: action.payload};
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM