Redux Saga动作崩溃应用程序

时间:2018-05-21 14:57:46

标签: reactjs redux redux-saga

我有一个简单的React / Redux / Redux Sagas应用程序,它使用API​​在点击按钮时显示狗的随机图片。

dogSagas.js

import { put, call, takeEvery, all } from 'redux-saga/effects';
import * as types from '../actions/types';
import * as actions from '../actions/dogActions';
import { DOG_API } from '../constants/variables';

function* getDogAsync() {
  try {
    yield put(actions.getDog);

    const data = yield call(() =>
      fetch(DOG_API)
        .then(res => res.json())
        .catch(err => console.error(err)),
    );

    yield put(actions.getDogOk(data));
  } catch (error) {
    yield put(actions.getDogFail());
  }
}

function* watchGetDog() {
  yield takeEvery(types.GET_DOG, getDogAsync);
}

export default function* rootSaga() {
  yield all([watchGetDog()]);
}

dogActions.js

import * as types from '../actions/types';

export const getDog = () => ({
  type: types.GET_DOG,
});

export const getDogOk = data => ({
  type: types.GET_DOG_OK,
  payload: data.message,
});

export const getDogFail = () => ({
  type: types.GET_DOG_FAIL,
});

错误

但是,我有两个不同的错误。

1。)当我yield put(actions.getDog);该应用程序正常工作时,但在控制台中我收到错误:

uncaught at getDogAsync Error: Actions must be plain objects. Use custom middleware for async actions.

2。)如果我这样做:yield put(actions.getDog());该应用消耗大量CPU并有效崩溃。

问题

所以,我的问题是:

1。)为什么这种方法会导致Redux抱怨非普通对象?

2。)为什么这个看似无害的声明导致应用程序崩溃?

完整代码

StackBlitz上的完整代码here

1 个答案:

答案 0 :(得分:0)

问题是我在异步生成器getDog()中调用getDogAsync()操作创建者。由于我们有一个观察者,这导致无数次调用getDog()

所以,要修复,只需删除:

yield put(actions.getDog);
getDogAsync()