如何使用runSaga启动Redux Saga Watcher [英] How to start a redux saga watcher using runSaga
问题描述
我无法从文档中了解如何使用runSaga启动redux saga观察器.假设我在 saga.js
中具有以下内容:
I am not able to figure out from the documentation how to start a redux saga watcher using runSaga. Suppose I have the following in 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"?
I'm not able to trigger the api call using dispatch({ type: 'FETCH_JOKE' })
.
But when I use fetchJokeSaga
directly as runSaga({ dispatch, getState: store.getState }, fetchJokeSaga);
, it makes the api call immediately.
How do I dynamically start watcherSaga
so that I can dispatch 'FETCH_JOKES' later?
推荐答案
azundo几乎可以解决.您需要在频道中"投放"一些操作才能启动生成器.
azundo almost had the solution. You need to 'put' some actions in the channel to get the generator started.
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;
};
希望这会有所帮助.
这篇关于如何使用runSaga启动Redux Saga Watcher的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!