【发布时间】:2021-10-11 08:29:27
【问题描述】:
我试图理解redux saga的艺术,但遇到这种情况:
我有正常工作的 useEffect 钩子(更改 url 参数时工作一次)。这个钩子只调度一次动作(由 redux-saga-routines 创建)。
const params = useParams().params;
useEffect(() => {
if (urlTriggers.some(item => item === params)) {
dispatch(setItemsCollection({ itemType: params }));
toggleVisibleMode(true);
} else {
toggleVisibleMode(false);
}
}, [params]);
Saga watcher 对分派的动作做出反应
export function* setItemsCollectionWatcher() {
yield takeEvery(setItemsCollection.TRIGGER, setItemsCollectionWorker);
}
然后调用saga worker
function* setItemsCollectionWorker(action) {
const { itemType } = action.payload;
try {
yield put(toggleIsFetching({ isFetching: true }));
const itemsCollection = yield call(() => {
return axios.get(`http://localhost:60671/api/items/${itemType}/?page=1&count=2`).then(response => response.data.items);
});
yield put(setItemsCollection.success({ itemsCollection }));
yield put(toggleIsFetching({ isFetching: false }));
} catch (error) {
console.log(error);
} finally {
yield put(setItemsCollection.fulfill());
}
}
这个传奇倾听所有传奇观察者
export default function* saga() {
yield all([
setBackgroundWatcher(),
setItemsCollectionWatcher(),
])
}
传奇奔跑
sagaMiddleware.run(saga);
export const setItemsCollection = createRoutine('showcase/SET_ITEMS_COLLECTION');
export const toggleIsFetching = createRoutine('showcase/TOGGLE_IS_FETCHING');
const showcase = createReducer(
{
itemsCollection: [],
isFetching: false,
},
{
[setItemsCollection.SUCCESS]: (state, action) => {
state.itemsCollection = action.payload.itemsCollection;
},
[toggleIsFetching.TRIGGER]: (state, action) => {
state.isFetching = action.payload.isFetching;
},
}
);
但我有 2 个 axios 请求,而不是只有一个。
【问题讨论】:
-
你确定 useEffect 吗?在 dispatch(setItemsCollection({ itemType: params })) 之前放置一个 console.log('test');并确认 console.log 会出现一次。
-
如果你在上面没有看到两个
console.log,你是否看到在 Redux Devtools 中记录了两次操作? -
@novonimo ,console.log 只出现过一次。 'if' 条件防止调度被执行两次。
-
@chris ,在 Redux Devtools 中有两个 show/SET_ITEMS_COLLECTION/TRIGGER 和相同数量的 show/SET_ITEMS_COLLECTION/SUCCES :)
-
好吧,再进一步,你确定“SET_ITEMS_COLLECTION”动作只用在这个saga中还是你在reducer上使用了它,其他sagas错误?
标签: reactjs redux redux-saga