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中监测使用