React Redux中Reducer错误互扰问题求助:SuccessModal操作意外影响LoginModal Reducer
Hey there! Let's break down the issues in your code that are causing this unexpected behavior:
1. Critical mistake in successModalReducer
Your successModalReducer is switching on the entire action object instead of action.type:
// Wrong: compares action object to string case values switch (action) {
Redux actions are objects with a type property, so you need to check action.type instead. Right now, none of your case conditions will ever match, so the reducer always hits the default branch and resets the state. Even worse, your default branch is creating a brand new state object every time—this can cause unintended side effects when unrelated actions are dispatched.
Fix this by updating the switch statement and default branch:
const successModalReducer = (state = {opacity: 0, pointerEvents: 'none'}, action) => { switch (action.type) { // Changed to action.type case 'SUCCESS_MODAL_APPEAR': return {opacity: 1, pointerEvents: 'all'}; // No need to assign to state first case 'SUCCESS_MODAL_DISAPPEAR': return {opacity: 0, pointerEvents: 'none'}; default: return state; // Return existing state instead of resetting it } };
2. Typo in loginModalReducer action type + problematic default branch
First, there's a typo in your login modal's disappear case:
case 'LOGIN_MODAL_DISSAPEAR': // Has an extra 's'
But your action creator uses:
export const loginModalDisappear = () => { return { type: 'LOGIN_MODAL_DISAPPEAR', // Only one 's' in DISAPPEAR }; };
This typo means when you dispatch loginModalDisappear(), the reducer can't find a matching case.
Worse, your loginModalReducer also resets the state in its default branch instead of returning the existing state. That means every time any action is dispatched (including success modal actions), if it doesn't match the login modal's cases, the default branch runs and resets the login modal state to {opacity: 0, pointerEvents: 'none'}—this is exactly why your success modal actions are affecting the login modal.
Fix both issues here:
const loginModalReducer = (state = {opacity: 0, pointerEvents: 'none'}, action) => { switch (action.type) { case 'LOGIN_MODAL_APPEAR': return {opacity: 1, pointerEvents: 'all'}; case 'LOGIN_MODAL_DISAPPEAR': // Fixed the typo return {opacity: 0, pointerEvents: 'none'}; default: return state; // Return existing state instead of resetting } };
3. Bonus: Clean up redundant syntax
You don't need to assign the new state to state before returning it (e.g., return state = { ... }). Just return the new object directly—it's cleaner and more idiomatic Redux practice.
After fixing these issues, dispatch your success modal actions and they shouldn't affect the login modal anymore. If you're still having problems, feel free to share your root reducer (where you combine the reducers) and any component code that uses these modals!
内容的提问来源于stack exchange,提问作者domishady

