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

React中使用useState setter无法更新后端获取的数组问题求助

问题:无法将后端返回的数组更新到useState空数组中

我正在做个人项目,遇到一个问题:能从后端获取到数组,但用useState的setter函数更新空数组时完全没效果。已经卡了3小时,很挫败。附上我的React代码:

import { useEffect, useState } from "react";
import axios from "axios";
import toast from "react-hot-toast";

const UseGetconversation = async () => {
  const [loading, setloading] = useState(false);
  const [Conversations, setConversations] = useState([]);

  useEffect(() => {
    const getconversation = async () => {
      setloading(true);
      try {
        const res = await axios.get("api/users/");
        if (res.error) {
          throw new Error(res.error);
        }
        const data = res.data;
        console.log(data);
        console.log(Array.isArray(data));
        setConversations(data);
        console.log(Conversations);
      } catch (error) {
        toast.error(error.message);
      } finally {
        setloading(false);
      }
    };

    getconversation();
  }, []);

  return { loading, Conversations };
};

export default UseGetconversation;

解决方案
  • 移除自定义Hook的async关键字
    自定义Hook本质是普通函数,React禁止用async声明Hook,这会打乱Hook的执行顺序,直接导致state更新失效。

  • 正确看待useState的异步性
    setConversations(data)后立刻console.log(Conversations)打印的是旧值,因为useState更新是异步批量处理的。要查看更新后的state,可添加监听:

useEffect(() => {
  console.log("更新后的Conversations:", Conversations);
}, [Conversations]);
  • 修正Axios错误处理与请求路径
    Axios请求失败会直接进入catch块,res.error判断无效;同时请求路径建议开头加/,避免相对路径问题:
try {
  const res = await axios.get("/api/users/");
  const data = res.data;
  setConversations(data);
} catch (error) {
  toast.error(error.response?.data?.message || error.message);
}

修改后的完整代码:

import { useEffect, useState } from "react";
import axios from "axios";
import toast from "react-hot-toast";

const UseGetconversation = () => {
  const [loading, setloading] = useState(false);
  const [Conversations, setConversations] = useState([]);

  useEffect(() => {
    const getconversation = async () => {
      setloading(true);
      try {
        const res = await axios.get("/api/users/");
        const data = res.data;
        console.log(data);
        console.log(Array.isArray(data));
        setConversations(data);
      } catch (error) {
        toast.error(error.response?.data?.message || error.message);
      } finally {
        setloading(false);
      }
    };

    getconversation();
  }, []);

  useEffect(() => {
    console.log("Conversations更新完成:", Conversations);
  }, [Conversations]);

  return { loading, Conversations };
};

export default UseGetconversation;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 19:57:07