Redux传奇:撰写Sagas

问题描述 投票:0回答:1

我有一个networkSaga,可以在其中获取帖子,添加和删除喜欢的内容。添加或删除了点赞后,我需要致电getPosts更新点赞的数量。

在redux-thunk中,我将在添加或删除类似内容后直接调用dispatch(getPosts())。因为,我是sagas的新手,所以很担心,应该怎么做?

import { all, call, fork, put, takeEvery } from 'redux-saga/effects';
import { NetworkActionTypes } from './types';
import { apiCaller } from '../../utils/apiCaller';
import { onSuccess, onFailure } from '../../utils/actionCreators';

function* getPosts(action): Generator {
  try {
    const res = yield call(apiCaller, action.meta.method, action.meta.route, action.meta.data);

    yield put(onSuccess(NetworkActionTypes.GET_POSTS_SUCCESS, res));
  } catch (err) {
    yield put(onFailure(NetworkActionTypes.GET_POSTS_ERROR, err));
  }
}

function* addLike(action): Generator {
  try {
    const res = yield call(apiCaller, action.meta.method, action.meta.route, action.meta.data);

    yield put(onSuccess(NetworkActionTypes.ADD_LIKE_SUCCESS, res));
  } catch (err) {
    yield put(onFailure(NetworkActionTypes.ADD_LIKE_ERROR, err));
  }
}

function* removeLike(action): Generator {
  try {
    const res = yield call(apiCaller, action.meta.method, action.meta.route, action.meta.data);

    yield put(onSuccess(NetworkActionTypes.REMOVE_LIKE_SUCCESS, res));
  } catch (err) {
    yield put(onFailure(NetworkActionTypes.REMOVE_LIKE_ERROR, err));
  }
}

/**
 * @desc Watches every specified action and runs effect method and passes action args to it
 */
function* watchFetchRequest(): Generator {
  yield takeEvery(NetworkActionTypes.GET_POSTS, getPosts);
  yield takeEvery(NetworkActionTypes.ADD_LIKE, addLike);
  yield takeEvery(NetworkActionTypes.REMOVE_LIKE, removeLike);
}

/**
 * @desc saga init, forks in effects, other sagas
 */
export function* networkSaga() {
  yield all([fork(watchFetchRequest)]);
}

这个问题听起来很愚蠢,但是如果您指出我的解决方法,我将不胜感激。谢谢!

reactjs redux redux-saga
1个回答
0
投票

一旦从yield getPosts(action json you have to pass here) api获得成功,您就可以通过add/remove来做。

© www.soinside.com 2019 - 2024. All rights reserved.