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

React函数组件使用axios发起GET请求后无法正常setState问题求助

React函数组件状态使用问题修正

核心错误点

  • 函数组件不存在this,类组件的this.state写法完全不适用函数组件,useState返回的状态变量可以直接读取
  • useState初始值类型不匹配:你初始赋值是空字符串'',后续却存入{customer: 响应数据}的对象结构,类型完全不一致
  • useEffect未添加空依赖数组,会导致组件每次渲染都重复调用send接口,出现无限请求的问题
  • 你已经用Redux存储了用户数据,其实无需再单独存到组件内部state,直接从Redux取值更符合项目规范

修正方案1:仅使用组件内部state存储数据

import { useState, useEffect } from 'react';
import axios from 'axios';
import CustomerModel from './你的路径/CustomerModel';

// 定义状态类型,包含用户信息和优惠券数组
interface CustomerState {
  // 后端返回的字段包含CustomerModel属性+coupons数组,可自行替换coupons的具体类型
  customer: CustomerModel & { coupons: any[] };
}

function GetCustomerDetailsFc(props: CustomerModel): JSX.Element {
  // 初始化state,初始值设为null方便后续判断加载状态
  const [state, setState] = useState<CustomerState | null>(null);

  async function send(){
    try {
      const response = await axios.get<CustomerModel & { coupons: any[] }>(globals.urls.customerDetails);
      store.dispatch(oneCustomerAction(response.data));
      console.log(response.data);
      // 将数据存入state
      setState({ customer: response.data });
    } catch (err) {
      notify.error(err);
    }
  }

  // 添加空依赖数组,只在组件挂载时执行一次接口请求
  useEffect(() => {
    send();
  }, []);

  // 加载状态判断,避免state为空时读取属性报错
  if (!state) return <div>加载中...</div>;

  return (
    <>
      <h1>{state.customer.email}</h1>
      {/* 读取优惠券数组示例 */}
      <div>购买记录数量:{state.customer.coupons.length}</div>
    </>
  );
}

export default GetCustomerDetailsFc;

修正方案2:适配项目Redux规范,直接从Redux取值

你已经将用户数据dispatch到Redux存储,无需额外维护组件内部state,直接从Redux取值更合理:

import { useEffect } from 'react';
import axios from 'axios';
import { useSelector } from 'react-redux';
import CustomerModel from './你的路径/CustomerModel';

function GetCustomerDetailsFc(props: CustomerModel): JSX.Element {
  // 从Redux中读取存储的用户数据,替换state.oneCustomer为你自己的Redux状态路径
  const customer = useSelector(state => state.oneCustomer);

  async function send(){
    try {
      const response = await axios.get<CustomerModel & { coupons: any[] }>(globals.urls.customerDetails);
      store.dispatch(oneCustomerAction(response.data));
    } catch (err) {
      notify.error(err);
    }
  }

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

  if (!customer) return <div>加载中...</div>;

  return (
    <>
      <h1>{customer.email}</h1>
      <div>购买记录数量:{customer.coupons.length}</div>
    </>
  );
}

export default GetCustomerDetailsFc;

内容的提问来源于stack exchange,提问作者Shai Ace

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:36:03