【发布时间】:2021-08-28 12:50:11
【问题描述】:
所以我得到了这个 useEffect 函数:
useEffect(
() => {
getDoH().then((response) => {
initialResponse.current = response.data;
console.log(response.data)
}, (error) => {
console.log(error);
});
console.log(initialResponse.current)
}, []);
getDoH 是 axios.get 函数,initialResponse 是:
const initialResponse = useRef();
我用它来避免一些问题。 关键是页面在第一次渲染时从我的后端获取一组值并将其保存在“initialResponse”中,以便稍后在其他函数中使用它。
但我的
console.log(initialResponse.current)
继续以“Undfeined”的形式返回,换句话说,我似乎无法将我的响应值保存到其中。知道为什么或如何解决它吗?
【问题讨论】:
-
它不会出现,因为
.then在你的 console.log 运行之后运行,因为它是一个承诺。为什么不将其存储在状态中? -
我敢肯定,如果您查看您的
log订单,您的第三个日志会在第一个之前打印。
标签: reactjs axios react-hooks use-effect use-ref