无法在React中的嵌套Axios Post请求中固定
我正在尝试从嵌套的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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在React中设置状态就像异步函数。
这意味着当您设置状态并在其示例中,
console.log
函数在状态实际完成更新之前运行时,请立即设置状态并放置console.log
。这就是为什么我们具有
使用
的原因,这是一个内置的react钩子,当它的依赖项之一更改时,它会激活回调。示例:
每次状态值更改时,回调才会运行,并且只有在变化并发生渲染后才进行。
编辑:
根据评论中的讨论。
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, theconsole.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:
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.
由于SetState是一项异步任务,因此您不会直接看到更改。
如果您想在Axios调用后查看更改,则可以使用以下代码:
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 :