如何使用 runSaga 启动 redux saga watcher

IT技术 reactjs redux generator redux-saga
2021-04-30 21:03:59

我无法从文档中弄清楚如何使用 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”?

2个回答

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;
};

希望这可以帮助。

由于您的watcher传奇正在使用take效果,因此需要channel聆听。除非你正在做一些定制你想要的正常stdChannelredux-saga提供:

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

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

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

  return joke;
};