提取后无法设置反应

发布于 2025-02-01 18:14:57 字数 1061 浏览 2 评论 0 原文

我有一个组件,在成功获取后,我想渲染一些数据,但是即使成功获取后,SetState也无法正常工作。即使是“ console.log(wendesp.data)”也显示了正确的对象,但是为什么“ setGroupData(wendesp.data)”行上方的“ setGroupData(wendesp.data)”行不会更改状态?,而是返回一个空对象。

这是代码:

const GroupContent = ({ groupContent, changeGroupTitle }) => {
  const groupId = window.location.href.split(
    "http://localhost:3001/groups/"
  )[1];
  const [groupData, setGroupData] = useState({});
  let token = "";

  const getGroupData = async () => {
    token = await localStorage.getItem("token");

    if (token) {
      try {
        const auth = `Bearer ${token}`;
        // console.log(auth);
        const response = await axios.get(`/api/groups/${groupId}`, {
          headers: {
            Authorization: auth,
          },
        });
        console.log(response.data);
        setGroupData(response.data);
        console.log(groupData);
        changeGroupTitle(groupData.title);
      } catch (err) {
        console.log(err.response);
      }
    }
  };

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

I have a component, where i want to render some data after it is successfully fetched, but the SetState Wont Work even after a successful fetch. Even a 'console.log(response.data)' is showing the right object, but Why the 'setGroupData(response.data)' line below it wont change the state?, but returning an empty object instead.

here is the code :

const GroupContent = ({ groupContent, changeGroupTitle }) => {
  const groupId = window.location.href.split(
    "http://localhost:3001/groups/"
  )[1];
  const [groupData, setGroupData] = useState({});
  let token = "";

  const getGroupData = async () => {
    token = await localStorage.getItem("token");

    if (token) {
      try {
        const auth = `Bearer ${token}`;
        // console.log(auth);
        const response = await axios.get(`/api/groups/${groupId}`, {
          headers: {
            Authorization: auth,
          },
        });
        console.log(response.data);
        setGroupData(response.data);
        console.log(groupData);
        changeGroupTitle(groupData.title);
      } catch (err) {
        console.log(err.response);
      }
    }
  };

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风吹短裙飘 2025-02-08 18:14:57

SetState工作正常,但是更新本质上是异步的。您可以在此处做几件事

  1. convert setGroupData(response.data) to setGroupData((()=>({... {... response.data}})>

  2. 使用使用 groupData 在依赖性数组中。

如果我是您,我会更改的其他一些事情:

  • 本地存储或会话存储操作不是异步的。我将在LocalStorage操作之前删除等待的等待,
  • 我将功能getGroupData重命名为其他令人困惑的东西,例如。 fetchgroupdata

但这是我的个人喜好,前两个指针将有效

The setState is working fine but the update is asynchronous in nature. You can do couple of things here

  1. Convert setGroupData(response.data) to setGroupData(() => ({...response.data}})

  2. Listen to state change using useEffect with groupData in the depenency array.

Here's some other things which I'd change if I were you:

  • Local Storage or session storage operations are not asynchronous. I'd remove the await before the localStorage operation
  • I'd rename the function getGroupData to something else that is less confusing, eg. fetchGroupData

But these are my personal preferences, the first two pointers will work

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文