首页 > 解决方案 > 如何使用 runSaga 启动 redux saga watcher

问题描述

我无法从文档中弄清楚如何使用 runSaga 启动 redux saga watcher。假设我有以下内容saga.js

export function* fetchJokeSaga(action) {
  try {
    const response = yield call(axios.get, "...");
    yield put({ type: "UPDATE_JOKE", payload: response });
  } catch (e) {}
}

export default function* watcherSaga(action) {
  yield takeEvery("FETCH_JOKE", fetchJokeSaga);
}

以及以下内容Component.js

const Component = () => {
  const store = useStore();
  const dispatch = useDispatch();
  const { joke } = useSelector(state => state);

  React.useEffect(() => {
    runSaga({ dispatch, getState: store.getState }, watcherSaga);
  }, []);

  return joke;
};

我无法使用dispatch({ type: 'FETCH_JOKE' }).
但是当我fetchJokeSaga直接使用 as时runSaga({ dispatch, getState: store.getState }, fetchJokeSaga);,它会立即进行 api 调用。
如何动态启动watcherSaga,以便稍后分派“FETCH_JOKES”?

标签: reactjsreduxgeneratorredux-saga

解决方案


azundo 几乎找到了解决方案。您需要在通道中“放置”一些操作以启动生成器。

import {stdChannel, runSaga} from 'redux-saga';

const Component = () => {
   const store = useStore();
   const dispatch = useDispatch();
   const { joke } = useSelector(state => state);

   React.useEffect(() => {
       const channel = stdChannel();
       runSaga({ dispatch, getState: store.getState, channel}, watcherSaga);
       channel.put({ type: 'FETCH_JOKE' });
   }, []);

   return joke;
};

希望这可以帮助。


推荐阅读