无法在React中的嵌套Axios Post请求中固定

发布于 2025-02-04 12:15:08 字数 900 浏览 2 评论 0原文

我正在尝试从嵌套的axios.post调用访问res.data.id,并将其分配给'activeId'变量。我在按钮点击事件上调用handlesaveall()函数。单击按钮时,当我安装“ res.data.id”时,它正确返回值,但是当我安装'activeId'时,它返回null,这意味着无法分配“ res.data.id” 。有人有解决方案吗?提前致谢

const [activeId, setActiveId] = useState(null);

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

const save1 = () => {
      axios.get(api1, getDefaultHeaders())
        .then(() => {
          const data = {item1: item1,};

          axios.post(api2, data, getDefaultHeaders()).then((res) => {
            setActiveId(res.data.id);
            console.log(res.data.id); // result: e.g. 10
          });
      });
};

const save2 = () => {
  console.log(activeId); // result: null
};

const handleSaveAll = () => {
  save1();
  save2();

  console.log(activeId); // result: again its still null
};

return (
  <button type='submit' onClick={handleSaveAll}>Save</button>
);

I am trying to access the res.data.id from a nested axios.post call and assign it to 'activeId' variable. I am calling the handleSaveAll() function on a button Click event. When the button is clicked, When I console the 'res.data.Id', its returning the value properly, but when I console the 'activeId', it's returning null, which means the 'res.data.id' cannot be assigned. Does anyone have a solution? Thanks in advance

const [activeId, setActiveId] = useState(null);

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

const save1 = () => {
      axios.get(api1, getDefaultHeaders())
        .then(() => {
          const data = {item1: item1,};

          axios.post(api2, data, getDefaultHeaders()).then((res) => {
            setActiveId(res.data.id);
            console.log(res.data.id); // result: e.g. 10
          });
      });
};

const save2 = () => {
  console.log(activeId); // result: null
};

const handleSaveAll = () => {
  save1();
  save2();

  console.log(activeId); // result: again its still null
};

return (
  <button type='submit' onClick={handleSaveAll}>Save</button>
);

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

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

发布评论

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

评论(2

青芜 2025-02-11 12:15:08

在React中设置状态就像异步函数。
这意味着当您设置状态并在其示例中,console.log函数在状态实际完成更新之前运行时,请立即设置状态并放置console.log

这就是为什么我们具有使用的原因,这是一个内置的react钩子,当它的依赖项之一更改时,它会激活回调。

示例:

useEffect(() => {
   console.log(activeId);
}, [activeId);

每次状态值更改时,回调才会运行,并且只有在变化并发生渲染后才进行。


编辑:

根据评论中的讨论。

const handleSaveSections = () => {
   // ... Your logic with the `setState` at the end.
}

useEffect(() => {
   if (activeId === null) {
      return;
   }
   save2(); // ( or any other function / logic you need )
}, [activeId]);

return (
   <button onClick={handleSaveSections}>Click me!</button>
)

Setting the state in React acts like an async function.
Meaning that the when you set the state and put a console.log right after it, like in your example, the console.log function runs before the state has actually finished updating.

Which is why we have useEffect, a built-in React hook that activates a callback when one of it's dependencies have changed.

Example:

useEffect(() => {
   console.log(activeId);
}, [activeId);

The callback will run every time the state value changes and only after it has finished changing and a render has occurred.


Edit:

Based on the discussion in the comments.

const handleSaveSections = () => {
   // ... Your logic with the `setState` at the end.
}

useEffect(() => {
   if (activeId === null) {
      return;
   }
   save2(); // ( or any other function / logic you need )
}, [activeId]);

return (
   <button onClick={handleSaveSections}>Click me!</button>
)
凤舞天涯 2025-02-11 12:15:08

由于SetState是一项异步任务,因此您不会直接看到更改。
如果您想在Axios调用后查看更改,则可以使用以下代码:

       axios.post(api2, data, getDefaultHeaders())
        .then((res) => {
         setActiveId(res.data.id)
         console.log(res.data.id) // result: e.g. 10
         setTimeout(()=>console.log(activeId),0);
      })

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

const [activeId, setActiveId] = useState(null);

const save1 = () => {
    const handleSaveSections = async () => {
        activeMetric &&
            axios.get(api1, getDefaultHeaders()).then(res => {
                if (res.data.length > 0) {
                    Swal.fire({
                        text: 'Record already exists',
                        icon: 'error',
                    });
                    return false;
                }
                else {
                    const data = {
                        item1: item1,
                        item2: item2
                    }

                    axios.post(api2, data, getDefaultHeaders())
                        .then((res) => {
                            setActiveId(res.data.id)
                            console.log(res.data.id) // result: e.g. 10
                        })
                }
            });
    }
handleSaveSections()
}

const save2 = () => {
    console.log(activeId);   //correct result would be shown here
}

const handleSaveAll = () => {
    save1();
    save2();
}
 
return (
    <button type="submit" onClick={handleSaveAll}>Save</button>
)

As the setState is a async task, you will not see the changes directly.
If you want to see the changes after the axios call, you can use the following code :

       axios.post(api2, data, getDefaultHeaders())
        .then((res) => {
         setActiveId(res.data.id)
         console.log(res.data.id) // result: e.g. 10
         setTimeout(()=>console.log(activeId),0);
      })

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

const [activeId, setActiveId] = useState(null);

const save1 = () => {
    const handleSaveSections = async () => {
        activeMetric &&
            axios.get(api1, getDefaultHeaders()).then(res => {
                if (res.data.length > 0) {
                    Swal.fire({
                        text: 'Record already exists',
                        icon: 'error',
                    });
                    return false;
                }
                else {
                    const data = {
                        item1: item1,
                        item2: item2
                    }

                    axios.post(api2, data, getDefaultHeaders())
                        .then((res) => {
                            setActiveId(res.data.id)
                            console.log(res.data.id) // result: e.g. 10
                        })
                }
            });
    }
handleSaveSections()
}

const save2 = () => {
    console.log(activeId);   //correct result would be shown here
}

const handleSaveAll = () => {
    save1();
    save2();
}
 
return (
    <button type="submit" onClick={handleSaveAll}>Save</button>
)

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