You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:React中Context+useReducer的Reducer无法更新状态问题

使用Context + useReducer状态管理时状态无法更新的问题修复

问题场景

使用Context和useReducer替代Redux进行状态管理时,dispatch的数据能成功到达Reducer(通过Console.log可确认),但初始状态始终无法更新。当注册接口返回{ok: false, msg: 'El usuario ya existe'}的错误结果时,Reducer始终返回初始状态。

相关代码

App.js

import { RouterProvider } from "react-router-dom";
import { router } from "./router";
import { AuthProvider } from "./authpage/AuthContext";
import { AuthReducer, initialState } from "./authpage/AuthReducer";

function App() {
  return (
    <AuthProvider initialState={initialState} AuthReducer={AuthReducer}>
      <RouterProvider router={router} />
    </AuthProvider>
  );
}

export default App;

AuthContext.js

import { createContext, useReducer } from "react";
export const AuthContext = createContext();

export const AuthProvider = ({ AuthReducer, initialState, children }) => {
  return (
    <AuthContext.Provider value={useReducer(AuthReducer, initialState)}>
      {children}
    </AuthContext.Provider>
  );
};

LoginSignIn组件

import { register } from "./authActions";

import { AuthContext } from "./AuthContext";
import { types } from "../types";

export const LoginSignIn = () => {

 const [state, dispatch] = useContext(AuthContext);
  const registerSubmit = async () => {
    const body = await register(registerName, registerEmail, registerPassword);

    body.user
      ? dispatch({ type: types.AUTH_REGISTER, payload: body.user })
      : dispatch({ types: types.AUTH_ERROR, payload: body.msg });

    console.log(body);
  };

  return (
    <>
      <h1>FORM</h1>

      <form submit={registerSubmit}>
        <buttton submit={registerSubmit}></buttton>
      </form>
    </>
  );
};

AuthReducer.js

import { types } from "../types";
export const initialState = {
  checking: true,
  uid: null,
  user: null,
  msg: null,
};

export const AuthReducer = (state = initialState, action) => {
  console.log(action.payload);
  console.log(action);

  switch (action.type) {
    case types.AUTH_REGISTER:
      return {
        ...state,
        user: action.payload,
        checking: false,
      };
    case types.AUTH_ERROR:
      console.log("estos es");
      return {
        ...state,
        ...action.payload,
        msg: action.payload,
        checking: false,
      };

    default:
      return state;
  }
};

问题根源

在LoginSignIn组件的错误分支dispatch中,误将type拼写为types:

// 错误写法
dispatch({ types: types.AUTH_ERROR, payload: body.msg });

这导致Reducer的switch语句无法匹配到types.AUTH_ERROR分支,只能进入default逻辑返回初始状态。

修复方案

将错误分支的types改为type,确保action的type字段正确:

// 正确写法
dispatch({ type: types.AUTH_ERROR, payload: body.msg });

内容的提问来源于stack exchange,提问作者ISMILIRDS IO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 06:12:46