【发布时间】:2020-09-12 23:53:41
【问题描述】:
我最近学习了 MERN 堆栈,目前正在使用它制作一个副项目。我遇到了一个问题,每次调用不同的操作时,我的 Redux Reducer 都会相互覆盖。这是完整而详细的问题。
问题:
- 在 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