使用useEffect调用2个API时Redux状态被覆盖

时间:2020-04-05 16:33:33

标签: reactjs redux react-redux

我有2个调用不同API的操作。我将这些动作分派到useEffect中。
我有2个reducer文件,每个减少文件一个,用于存储从API接收的数据。
因此,基本上,我应该能够使用useState单独访问这两个数据。
但是,第二个API的数据将覆盖第一个API的数据。我不知道该怎么办,因为它们甚至不在同一个文件中,甚至没有关联。

组件

    const items = useSelector((state) => state.lostchambers.items);
    const lostChambersItems = useSelector((state) => state.sharklostdolsea.itemsLostChamber);

  useEffect(() => {
        dispatch(fetchingLostChambers());
        dispatch(fetchSharkLostDolSea());
    }, [dispatch]);

两个文件的操作看起来都像这样,我只在这里发布一个文件,因为它具有相同的代码

import { FETCH_POSTS } from "./type";
import axios from "../../utils/Request";

export const fetchingLostChambers = () => async (dispatch) => {
    const response = await axios.get("API");
    const { data = false, status } = response;
    if (status === 200) {
        if (data) {
            dispatch({
                type: FETCH_POSTS,
                items: data.acf,
            });
        }
    }
};

这两个动作的Reducer看起来像这样,但我只在这里发布一个文件,因为它具有相同的代码

import { FETCH_POSTS } from "../actions/lostchambers/type";

const initialState = {
    items: [],
};

export default (state = initialState, action) => {
    switch (action.type) {
        case FETCH_POSTS:
            return {
                ...state,
                ...action,
            };
        default:
            return state;
    }
};

组合减速器

import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import rootReducers from "./reducers";

const initialState = {};

const middleware = [thunk];

const store = createStore(rootReducers, initialState, applyMiddleware(...middleware));

export default store;

RootReducer

import { combineReducers } from "redux";
import venues from "./venues";
import lostchambers from "./lostchambers";
import sharklostdolsea from "./sharklostdolsea";

export default combineReducers({
    venues,
    lostchambers,
    sharklostdolsea,
});

我在这里想念什么吗?我只是想不通这个问题,我已经尝试了四个小时。

1 个答案:

答案 0 :(得分:2)

我在这里看到的主要问题是您为动作和化简使用了相同的类型常量。

redux的工作方式是,它将动作通过所有合并在一起的化合器进行,并且将运行化合器说发生的任何状态变化。这就是为什么在设置reducer时,如果没有匹配项,则需要基本情况​​返回状态。

通过在动作中使用相同的类型,两个reduce都将看到已调度的两个动作并执行更改。因此发生了争用情况,并且返回的最后一个情况同时显示在状态的两个部分。

您应该能够通过仅更改其中一个动作和两个动作的减速器类型常量来解决此问题。