我在fetch
钩子中有一个useEffect
。我正在控制台中登录其中的不同部分,并得到一些奇怪的结果
const [name, setName] = useState("Placeholder Name");
const [lat, setLat] = useState("Placeholder Lat");
const [long, setLong] = useState("Placeholder Long");
const [counter, setCounter] = useState(0);
const [loading, setLoading] = useState(true);
useEffect(() => {
console.log("top level");
fetch("https://api.wheretheiss.at/v1/satellites/25544")
.then(res => res.json())
.then(data => {
console.log("inside fetch", name, long, lat);
setName(data.name);
setLat(data.latitude);
setLong(data.longitude);
setLoading(false);
});
});
// Result on mount
top level
inside fetch Placeholder Name Placeholder Long Placeholder Lat
top level
top level
top level
top level
inside fetch iss Placeholder Long Placeholder Lat
inside fetch iss 71.768808134445 27.26618722337
top level
top level
inside fetch iss 71.815373509259 27.312786482746
安装组件时,我知道useEffect
会在状态值更新时运行。该API端点有1秒的限制,因此当其当前值与返回值匹配时,效果将停止运行。
我的具体困惑是,为什么在调用“访存”控制台日志之前连续记录了4次“顶层”。这可能与异步获取有关,但是我希望有人可以澄清一下。
答案 0 :(得分:1)
每次使用useState回调之一设置状态时,组件都会重新呈现。
您要连续设置4次状态值,因此组件可以非常快地连续刷新4次。每次渲染时,它都在调用useEffect挂钩,因为您没有一系列依赖项。由于该功能的其余部分是异步的
答案 1 :(得分:1)
默认情况下,由于react hooks doesn't batch state updates,下面是有关行为的分步说明:
top level // initial render
inside fetch Placeholder Name Placeholder Long Placeholder Lat // prior to re-render
top level // re-render: from setName()
top level // re-render: from setLat()
top level // re-render: from setLong()
top level // re-render: from setLoading()
inside fetch iss Placeholder Long Placeholder Lat // name updated
// The lines below could run infinitely every time long, lat changes
inside fetch iss 71.768808134445 27.26618722337 // long, lat updated
top level // re-render: new value for lat - setLat()
top level // re-render: new value for long - setLong()
inside fetch iss 71.815373509259 27.312786482746 // long, lat updated