【问题标题】:Behavior of Redux Reducer when Multiple Action is Called within A Component在组件内调用多个操作时 Redux Reducer 的行为
【发布时间】:2020-09-12 23:53:41
【问题描述】:

我最近学习了 MERN 堆栈,目前正在使用它制作一个副项目。我遇到了一个问题,每次调用不同的操作时,我的 Redux Reducer 都会相互覆盖。这是完整而详细的问题。

问题:

  1. 在 React 组件上调用操作的行为。假设我们决定创建一个动作并在我们的一个 React 组件中实现它,我们已经完成了所有设置(例如创建 reducer 并更新状态,创建动作本身并使用 @987654321 将其连接到 react 组件@来自react-redux)。我只是想知道当我从componentDidMount 调用我们的 React 组件中的多个操作时,为什么状态会相互覆盖。例如。
componentDidMount(){
  // Action updates 'user: {}' state in our reducer
  this.props.fetchUserData();
  // Action updates 'clients:{}' state 
  this.props.fetchClientsData();
}

Reducers 的结果状态:

user: {}, // Overrided by the fetchClientsData()
clients { clientsData }

我们不是在本质上更新特定的 reducer 状态吗(fetchUserData() 更新 'user:{}' 和 fetchClientsData() 更新 'clients: {}')。为什么它是压倒一切的?我检查了我的 Redux Devtools 中间件,它实际上是压倒一切的。我如何不覆盖减速器中的其他状态?谢谢!

更新: - 这是我的减速器: 索引.js

import { combineReducers } from "redux";
import AuthReducer from "./AuthReducer";
import NotificationReducer from "./NotificationReducer";
import { reducer as formReducer } from "redux-form";
import DataReducer from "./DataReducer";

export default combineReducers({
    form: formReducer,
    auth: AuthReducer,
    notification: NotificationReducer,
    data: DataReducer,
});

AuthReducer.js

import { FETCH_USER, FETCH_HOSPITAL } from "../actionTypes";

export default (state = null, action) => {
    switch (action.type) {
        case FETCH_USER:
            return action.payload || false;
        case FETCH_HOSPITAL:
            return action.payload || false;
        default:
            return false;
    }
};

DataReducer.js

import { FETCH_DATA } from "../actionTypes";

export default (state = {}, action) => {
    switch (action.type) {
        case FETCH_DATA:
            return { ...state, data: action.payload };
        default:
            return state;
    }
};

【问题讨论】:

  • 抱歉格式错误,由于某种原因,我无法用代码块封装“componentDidMount...”。
  • 你能分享你的减速机吗?
  • @IoannisPotouridis 我在上面的帖子中附上了我的减速器。希望尽快收到您的来信!
  • 抱歉,我之前没空,不过我很高兴发布了解决方案。

标签: reactjs redux react-redux


【解决方案1】:

错误在于您的AuthReducer,无论您从这些switch case 语句返回什么都将成为您的新状态。

与您在 DataReducer.js 文件中所做的相同

因此你必须像这样更新你的状态:

export default (state = null, action) => {
  switch (action.type) {
      case FETCH_USER:
          return {...state, users: action.payload || false};
      case FETCH_HOSPITAL:
          return {...state, clients: action.payload || false};
      default:
          return state;
  }
};

如果你能初始化你的状态也是一件好事

【讨论】:

  • 非常感谢您的解决方案。非常感谢
  • 很高兴能帮上忙 :)
猜你喜欢
  • 2016-12-15
  • 1970-01-01
  • 1970-01-01
  • 2018-05-07
  • 2017-10-03
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 2019-09-03
相关资源
最近更新 更多