redux-saga入门

详解请参考:https://github.com/redux-saga/redux-saga    and  https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html

store/index.js

import { createStore, applyMiddleware, compose } from 'redux'
import createSagaMiddleware from 'redux-saga'
import reducer from './reducer'
import TodoSagas from './sagas'

const sagaMiddleware = createSagaMiddleware();
const composeEnhancers =
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware));

const store = createStore(
  reducer,
  enhancer
);

sagaMiddleware.run(TodoSagas);

export default store;

store/sagas.js

import { takeEvery, put } from 'redux-saga/effects'
import axios from 'axios'
import {
  INIT_LIST
} from './actionType'
import {
  getInitListAction
} from './action'

const ERR_OK = 0;
function* getInitList() { try { const res = yield axios.get('http://122.51.241.68/api/list'); const data = res.data; if (data.rcode === ERR_OK) { const list = data.data const action = getInitListAction(list); yield put(action); } } catch(err) { console.log('网络请求失败:' + err) } } function* mySaga() { yield takeEvery(INIT_LIST, getInitList) } export default mySaga;

store/action.js

import {
  DELETE_LIST_ITEM,
  UPDATE_INPUT_VALUE,
  ADD_LIST_ITEM,
  INIT_LIST,
  GET_INIT_LIST
} from './actionType';

export const deleteListItemAction = (index) => ({
  type: DELETE_LIST_ITEM,
  index
})

export const updateInputValueAction = (value) => ({
  type: UPDATE_INPUT_VALUE,
  value
})

export const addListItemAction = (value) => ({
  type: ADD_LIST_ITEM,
  value
})

export const initListAction = (data) => ({
  type: INIT_LIST,
})

export const getInitListAction = (data) => ({
  type: GET_INIT_LIST,
  data
})

猜你喜欢

转载自www.cnblogs.com/ladybug7/p/12484264.html