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

改写Axios请求以处理返回对象数组中的无效数据

解决方案

1. 编写通用字符串清理函数

先实现一个工具函数,专门处理字符串的无效空格问题:

const cleanString = (str) => {
  // 非字符串类型直接返回,不处理数字、布尔值等非文本数据
  if (typeof str !== 'string') return str;
  
  // 把连续多空格替换为单个空格,再去除首尾空格
  const processedStr = str.replace(/\s+/g, ' ').trim();
  
  // 处理后为空(原内容全是空格)则返回null,否则返回清理后的字符串
  return processedStr === '' ? null : processedStr;
};

2. 处理接口返回的数据

根据接口返回的实际数据结构,分两种场景处理:

场景一:返回单个对象(当前代码中res.data.data为单个对象)

遍历对象的所有属性,对每个值应用清理函数:

const [values, setValues] = React.useState({} as any);

React.useEffect(() => {
  const fetchData = async () => {
    setLoading(true);
    try {
      const res = await axios.get(`${detailsUrl}${selectedRecord.id}`);
      
      // 遍历对象键值对,逐个清理字符串属性
      const cleanedData = Object.fromEntries(
        Object.entries(res.data.data).map(([key, value]) => [key, cleanString(value)])
      );
      
      setValues(cleanedData);
    } catch (error) {
      console.error(error.message);
      setValues(error.response.data);
    }
    setLoading(false);
  };
  fetchData();
}, []);

场景二:返回对象数组(你提到的"对象数组"场景)

如果接口返回的是数组,先遍历数组,再逐个处理每个对象的属性:

const [values, setValues] = React.useState([] as any[]);

React.useEffect(() => {
  const fetchData = async () => {
    setLoading(true);
    try {
      const res = await axios.get(`${detailsUrl}${selectedRecord.id}`);
      
      // 遍历数组内每个对象,清理其所有字符串属性
      const cleanedData = res.data.data.map(item => 
        Object.fromEntries(
          Object.entries(item).map(([key, value]) => [key, cleanString(value)])
        )
      );
      
      setValues(cleanedData);
    } catch (error) {
      console.error(error.message);
      setValues(error.response.data);
    }
    setLoading(false);
  };
  fetchData();
}, []);

关键说明

  • Object.entries() 将对象转为键值对数组,方便遍历处理;Object.fromEntries() 再将处理后的键值对数组转回对象
  • 正则/\s+/g会匹配所有连续空白字符(包括空格、制表符等),替换为单个空格,比原正则覆盖场景更全面
  • 非字符串类型数据会直接跳过处理,避免破坏原有数据类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 00:46:17