redux-saga简易使用

import React, { Component } from "react";
import { Text, View, Button } from "react-native";
import { createStore, applyMiddleware  } from "redux";

import { Provider, connect } from "react-redux";
import { put, takeEvery, delay, call } from 'redux-saga/effects'

import createSagaMiddleware from 'redux-saga'

const initialState = {
  numberA: 10,
  numberB: 20,
};

const incrementReducer = (state = initialState, action) => {
  switch (action.type) {
    case "TriggerA": {
      state.numberA += 1;
      return { ...state };
      break;
    }
    case "TriggerB": {
      state.numberB += 1;
      return { ...state };
      break;
    }
    default:
      return state;
  }
};


const sagaMiddleware = createSagaMiddleware() 
const store = createStore(incrementReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(watchIncrementAsync)

function* incrementAsyncA() {
  yield delay(2000)
  yield put({ type: 'TriggerA' })
}
//模拟请求
const ajax = () => new Promise(resolve=>setTimeout(()=>{
  console.log('返回数据')
  resolve()
}, 3000))
function* incrementAsyncB() {
  yield call(ajax)
  yield put({ type: 'TriggerB' })
}
function* watchIncrementAsync() {
  yield takeEvery('Trigger_Async_A', incrementAsyncA)
  yield takeEvery('Trigger_Async_B', incrementAsyncB)
}

class Box extends Component {
  constructor(props) {
    super(props);
  }
  onClick_A() {
    this.props.dispatch({ type: "TriggerA" });
  }
  onClick_B() {
    this.props.dispatch({ type: "TriggerB" });
  }
  onClick_Async_A() {
    this.props.dispatch({ type: "Trigger_Async_A" });
  }
  onClick_Async_B() {
    this.props.dispatch({ type: "Trigger_Async_B" });
  }
  render() {
    return (
      
        
          

你可能感兴趣的:(redux-saga简易使用)