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

使用useReducer搭配useContext时state始终为undefined如何解决

问题核心原因

  • reducer必须是同步纯函数,你在reducer内部执行异步请求projectget(),return语句写在异步回调里,reducer本身没有返回任何值,所以state自然被更新为undefined
  • 你直接修改了reducer的入参state,不符合不可变更新的规范,也会导致状态更新不触发组件重渲染
  • 重复发起了多余的请求:App组件的useEffect和Getprojects组件的useEffect都会触发add类型的dispatch,会重复请求接口

修复方案

1. 调整reducer逻辑,移除异步操作,只做同步状态更新

修改Usereducer.js:

const reducer = (state, action) => {
  if (action.type === 'add') {
    // 直接返回action携带的异步请求结果,reducer仅负责同步更新状态
    return action.payload;
  }
  // 未匹配的action统一返回原有state,避免返回undefined
  return state;
};
export default reducer;

2. 把异步请求移到组件内,请求完成后再把结果传给reducer

修改App.js:

import React, { createContext, useReducer, useEffect } from 'react';

import Uploadproject from './Uploadproject';
import Getprojects, { projectget } from './Getprojects';
import reducer from './reducer/Usereducer';

export const Contextstate = createContext();

const App = () => {
  // 初始值改为空数组,适配后续map操作,减少空值判断逻辑
  const initialvalue = [];
  const [state, dispatch] = useReducer(reducer, initialvalue);

  const updatestate = async () => {
    const data = await projectget();
    // 将请求结果放入payload传递给reducer
    dispatch({ type: 'add', payload: data });
  };

  useEffect(() => {
    updatestate();
  }, []);

  return (
    <>
      <Contextstate.Provider value={{ state, dispatch }}>
        <Uploadproject />
        <Getprojects />
      </Contextstate.Provider>
    </>
  );
};

export default App;

3. 移除Getprojects组件内重复的请求逻辑,补充缺失的方法导入

修改Getprojects.js:

import React, { useContext } from 'react';

import { Contextstate } from './App';
// 补充你原有代码中缺失的删除方法导入,替换为你的实际接口文件路径
import { deletproject } from '你的接口文件路径';

const Getprojects = () => {
  const { state } = useContext(Contextstate);

  return (
    <>
      <div>
        <h1>Projects</h1>
        {state.map((cur) => {
          return (
            <div key={cur._id}>
              <h1>{cur.title}</h1>
              <p>{cur.description}</p>
              <button
                onClick={() => {
                  deletproject(cur._id);
                }}
              >
                Delete
              </button>
            </div>
          );
        })}
      </div>
    </>
  );
};

export default Getprojects;

内容的提问来源于stack exchange,提问作者sujith kharvi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:15:03