2

我正在尝试在内部实现带有 redux-saga 的 React-boilerplate。所以我试图从服务器获取一些数据,然后重定向到另一个页面。问题是在重定向 saga 之前向服务器发出第二个请求。我想取消它有问题。这是我的代码的一部分:

export function* fetchData() {
  ...
  console.log('fetched');
  yield browserHistory.push('/another-page');
}

export function* fetchDataWatcher() {
  while (yield take('FETCH_DATA')) {
    yield call(fetchData);
  }
}

export function* fetchDataRootSaga() {
  const fetchWatcher = yield fork(fetchDataWatcher);

  yield take(LOCATION_CHANGE);
  yield cancel(fetchWatcher);
}

export default [
  fetchDataRootSaga
]

所以在这个例子中我有两个控制台日志,第二个出现在重定向之前。我该如何解决?

还有一个问题。实际上,我在这个文件中有更多的功能。我应该为它们中的每一个创建“rootSaga”还是可以在 fetchDataRootSaga() 中全部取消它们?我的意思是如果我以这种方式取消 sagas 是否正常:

export function* fetchDataRootSaga() {
  const watcherOne = yield fork(fetchDataOne);
  const watcherTwo = yield fork(fetchDataTwo);
  ...

  yield take(LOCATION_CHANGE);
  yield cancel(watcherOne);
  yield cancel(watcherTwo);
  ...
}

提前致谢!PS我不确定这段代码是否是最佳实践。它的灵感来自这个存储库

4

2 回答 2

1

也许首先调整你的循环内部fetchDataWatcher看起来更像这样

export function* fetchDataWatcher() {
  while (true) {
    yield take('FETCH_DATA');
    yield call(fetchData);
  }
}

你也可以通过做这样的事情来更好地路由

import { push } from 'react-router-redux';
import { put } from 'redux-saga/effects';

export function* fetchData() {
  ...
  console.log('fetched');
  yield put(push('/another-page'));
}

总体而言,我会犹豫put更改路线,然后完全单独take对其进行操作,前提是您希望取消所有位置更改(但我认为这就是您所追求的:))

于 2016-07-14T13:57:11.687 回答
0

这违背了 saga 的目的,即处理可能长时间运行的异步请求和返回。你可以像这样在你的 redux 商店中设置一个状态

export function* fetchData() {
  ...
  console.log('fetched');
  yield put(setRedirectState('/another-page'));
}

然后查看是否在 ComponentWillUpdate 中的容器中设置了重定向状态并相应地重定向到类似这样的内容

import { push } from 'react-router-redux';
dispatch(push(state.redirecturl))

我还没有尝试过,但是我对 React-boilerplate 的经验,这是我首先要尝试的。

于 2016-07-13T22:04:48.197 回答