【问题标题】:How to start a redux saga watcher using runSaga如何使用 runSaga 启动 redux saga watcher
【发布时间】:2019-09-09 17:26:50
【问题描述】:

我无法从文档中找出如何使用 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' }) 触发 api 调用。
但是当我直接将fetchJokeSaga 用作runSaga({ dispatch, getState: store.getState }, fetchJokeSaga); 时,它会立即调用api。
如何动态启动watcherSaga,以便稍后调度“FETCH_JOKES”?

【问题讨论】:

标签: reactjs redux generator redux-saga


【解决方案1】:

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

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    由于您的watcher saga 正在使用take 效果,它需要channel 来监听。除非你正在做一些自定义的事情,否则你会想要redux-saga 提供的普通stdChannel

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

    【讨论】:

    • 我尝试使用频道。但没有运气。我看到我的操作被调度,但观察者没有醒来进行 api 调用。
    • 正如这里提到的stackoverflow.com/a/60569822/6324591 我们需要在频道上调用put 来触发观察者:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多