如何解决saga已取消错误?

时间:2017-07-21 03:49:10

标签: reactjs redux redux-saga

我正在使用redux saga来处理我的异步操作。我在组件Mount上调用了actionCreator。但这个传奇被多次召唤。结果,api调用被连续调用。我该如何解决这个问题?

请在下面找到我的代码。

import { takeLatest, put, call } from 'redux-saga/effects';
import MyOrdersApi from 'yoda-interfaces/lib/MyOrders/MyOrders';
import * as MyOrdersActionTypes from '../actionTypes/MyOrdersActionTypes';

export function* myOrdersSaga(action){
   try {
     const myOrders = yield call(MyOrdersApi.getMyOrders);
     yield put({ type: MyOrdersActionTypes.GET_MY_ORDERS, myOrders })
   }
   catch(error){
     yield put({ type: MyOrdersActionTypes.GET_MY_ORDERS_ERROR, error })
   }

}

export default function* watchMyOrdersSaga() {
   yield takeLatest(MyOrdersActionTypes.GET_MY_ORDERS, myOrdersSaga);
}

1 个答案:

答案 0 :(得分:0)

问题是我从myOrdersSaga发出了同样的动作,我的watchMyOrdersSaga正在侦听,这使得它以递归方式调用api。正确的代码应该是

import { takeLatest, put, call } from 'redux-saga/effects';
import MyOrdersApi from 'yoda-interfaces/lib/MyOrders/MyOrders';
import * as MyOrdersActionTypes from '../actionTypes/MyOrdersActionTypes';

export function* myOrdersSaga(action){
   try {
     const myOrders = yield call(MyOrdersApi.getMyOrders);
     yield put({ type: MyOrdersActionTypes.GET_MY_ORDERS_SUCCESS, myOrders })
   }
   catch(error){
     yield put({ type: MyOrdersActionTypes.GET_MY_ORDERS_ERROR, error })
   }

}

export default function* watchMyOrdersSaga() {
   yield takeLatest(MyOrdersActionTypes.GET_MY_ORDERS, myOrdersSaga);
}