reactjs - 如何使用 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”?
解决方案
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;
};
希望这可以帮助。
推荐阅读
- mongodb - 获取嵌套关系数据 $lookup
- css - MBD导航栏元素下拉菜单中的悬停效果(材料设计引导程序)
- f# - 与内联函数一起使用时对象表达式的开销
- python - Python:在两个文件中查找字符串并打印所有行
- javascript - 如何预览像这个 logo.png 这样的文件名?
- azure - Azure Policy 类似架构的评估
- spring-boot - 由 CORS 阻止的 Spring Boot 自定义响应标头
- windows - 跨 Windows 版本的 HANDLE_TYPE_PROCESS
- java - 未调用 onCreateOptionsMenu
- java - 如何使用用户事务使用 Java 锁定 Postgres SQL 表显式