【问题标题】:Redux state gets overwritten when calling 2 API using useEffect使用 useEffect 调用 2 API 时 Redux 状态被覆盖
【发布时间】:2020-07-17 15:02:51
【问题描述】:

我有 2 个调用不同 API 的操作。我在 useEffect 中调度这些操作。
我有 2 个 reducers 文件,每个文件一个,用于存储从 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,
});

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

【问题讨论】:

  • 嘿,我在这里找到了。等待我的回答。不管怎样,你介意给我看看 combineReducers 部分吗?
  • 当然,我已将其添加到问题中
  • 我需要这个文件里面的部分:import rootReducers from "./reducers";
  • @CamSong 是的,我也添加了。看来你也遇到过这个问题

标签: reactjs redux react-redux


【解决方案1】:

我在这里看到的主要问题是您对动作和减速器使用相同的类型常量。

redux 的工作方式是将动作传递给所有组合在一起的 reducer,并运行 reducer 所说的任何状态更改。这就是为什么在设置 reducer 时,如果没有匹配项,则需要基本案例返回状态。

通过在动作中使用相同的类型,两个reducer 将看到已调度的两个动作并执行更改。因此会出现竞争条件,并且返回的最后一个条件会显示在状态的两个部分中。

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

【讨论】:

  • 很不错!看起来我错过了这部分。感谢您的知识!
  • @ThanveerShah 尽管文件是分开的,但最终它们都合并为一个文件,这是写在你的rootReducers 中的部分。所以重写是不可避免的。文件拆分只是人类的专利!
猜你喜欢
  • 1970-01-01
  • 2022-11-14
  • 2020-11-22
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 2020-12-30
  • 2019-12-07
  • 2019-07-19
相关资源
最近更新 更多