gpt4 book ai didi

reactjs - 如何使用 runSaga 启动 redux saga watcher

转载 作者:行者123 更新时间:2023-12-04 17:33:07 27 4
gpt4 key购买 nike

我无法从文档中弄清楚如何使用 runSaga 启动 redux saga 观察器。假设我在 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”?

最佳答案

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

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

希望这对您有所帮助。

关于reactjs - 如何使用 runSaga 启动 redux saga watcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57858622/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com