react基礎使用redux-saga

1、store中配置引入saga,還有saga.js的自定義文件

import { createStore, applyMiddleware, compose  } from 'redux'
import createSagaMiddleware from 'redux-saga' // 引入saga
import reducer from './reducer'
import mysaga from './saga' // 引入配置的saga.js文件
const sagaMiddleware = createSagaMiddleware() // 創建saga
const composeEnhancers =
  typeof window === 'object' &&
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;

const enhancer = composeEnhancers(
  applyMiddleware(sagaMiddleware),
)
const store = createStore(reducer, enhancer);
sagaMiddleware.run(mysaga) // 使用saga
export default store

2、在actionTypes中配置要調用的types

export const GET_HTTP_DATA = 'get_http_data' // 獲取網絡數據
export const INIT_LIST_DATA = 'init_list_data' // 初始化數據

3、在actionCreators中配置要派遣的action

export function getHttpData() {
  // 用於saga的檢測
  return {
    type: Types.GET_HTTP_DATA
  }
}

export function initListData(data) {
  // 初始化數據
  return {
    type: Types.INIT_LIST_DATA,
    value: data
  }
}

4、在需要派遣的地方調用action

componentDidMount() {
    // 在組件掛載在頁面上的時候
    store.dispatch(getHttpData())
  }

5、saga.js自定文件中監測到調用的action,做出相應的方法

import { takeEvery, put } from 'redux-saga/effects'
import * as Types from './actionTypes'
import { initListData } from './actionCreators'
import axios from 'axios'
function* getValue() {
  const  res = yield axios.get('https://api.apiopen.top/getJoke?page=1&count=2&type=video')
  const action = initListData(res.data)
  yield put(action) // 派遣對應的action
}

function* mySaga() {
   yield takeEvery(Types.GET_HTTP_DATA, getValue) // 監測到 對應類型action的派遣
}

export default mySaga

6、可在reducer.js中監測使用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章