【问题标题】:Redux saga is called twice with one dispatchRedux saga 在一次调度中被调用两次
【发布时间】: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


【解决方案1】:

您从客户端发送的类型为setItemsCollection,应该没问题(尽管我通常使用“USE_HUGE_OBVIOUS_TEXT_LIKE_THIS”)。你的 saga 中的 promise 的响应是相同的:setItemsCollection 然而,根据你要渲染的内容,你可能想用完全不同的东西来调用你的 reducer。

乍一看,我建议将此行更改为其他内容(并匹配减速器正在侦听的内容)。我想知道它是否在某处造成了交叉线。

【讨论】:

    猜你喜欢
    • 2019-08-15
    • 2018-09-06
    • 2019-12-03
    • 1970-01-01
    • 2016-10-12
    • 2021-06-22
    • 2019-12-01
    • 2023-04-02
    • 2018-09-03
    相关资源
    最近更新 更多