redux redux-saga實現異步方法

1、安裝
	cnpm install redux-saga --save
	
2、引入,在創建store的文件中引入
	import {createStore,applyMiddleware} from 'redux';
	import createSagaMiddleware from 'redux-saga'

3、創建中間件
	const sagaMiddleware = createSagaMiddleware()

4、使用中間件
	const store = createStore(
	  reducer,
	  applyMiddleware(sagaMiddleware)
	)

5、單獨創建一個saga文件來處理異步請求,內部使用es6的Generator函數然後導出

	當組件派發action後,saga也會接收到,通過匹配action中的type來進行相應操作
	所以引入action-type,目的是通過type來匹配
	引入actions.js,異步獲取到數據後通過同步的action來更新store的狀態
	
	import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
	import {x,xx} from './action-type'
	import {x1,xx1} from './actions'  對應reducer中的action,相當於使用redux-thunk時的同步action
	
	function* 回調方法()
	{
		異步操作
		try{
			const res=yield 異步方法;
			yield put(x1(res.data));   通過派發action更新數據
			
		}catch(e)
		{
			獲取數據失敗的情況
		}
		
		
	}
	
	function* xxx()
	{
		yield takeEvery(x,回調方法);
	}
	
	export defaut xxx
	
	
	 takeEvery:捕捉每一個action的類型,然後執行回調方法,支持併發同時處理多個相同action
	 takeLatest :不支持併發,如果之前已經有一個action在處理中,再執行一個相同的action,前面的action會被取消
	 put:相當於dispatch
	 call:用來調用函數,也可以不使用它,直接調用函數
	 	yield call(函數,參數1,參數2,..)

6、運行導出的saga中的函數,在創建的store文件中
	import xx from './x'
	
	sagaMiddleware.run(xx)

7、在action-type.js和actions.js中寫對應saga的相應代碼

	對應的type類型是saga用於接收的type,不是reducer,在saga中調用reducer的action來改變狀態
	actions.js中返回正常對象即可
		{type:xxx,data:xxx}

8、組件中派發用於saga的action
	import {y,yy} from '../redux/actions'
	
	props.y或store.dispatch.yy後,reducer和saga文件都會接收這個action
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章