next.js中的UseEffect钩子导致了2个获取请求,而我预计是1个,为什么



以下代码导致使用GET端点向我的API发出2个请求。我对useEffect((的理解不够,不知道从哪里开始调试,但我不想对这些API端点将调用服务器端的服务造成不必要的压力。这是因为他们将调用windows服务器来操作删除active directory等中的请求…

function Ad() {
const [data, setData] = useState(null)
const [isLoading, setLoading] = useState(false)
useEffect(() => {
setLoading(true)
fetch('../api/decom/ad')
.then(response => response.json())
.then(data => {
setData(data)
setLoading(false)
if (data.exists == true) {
Remove()
}
})
}, [])
const Remove = () => {
fetch("../api/decom/ad", { method: "DELETE" })
.then(response => response.json())
.then(data => {
var inner = ""
if (data.removed == true) {
inner = `<p>Removed: ${greenCircle}</p>`
} else {
inner = `<p>Removed: ${redCircle}</p>`
}
document.getElementById('adremoved').innerHTML = inner
})
}
if (data != null  && data.exists == true) return (
<a className={styles.card}>
<h2>AD</h2>
<p>Exists: { greenCircle } </p>
<div id ="adremoved" className={styles.parent}>
<p className={styles.child}>removed:</p>
<div><div className={styles.loader}><div></div><div></div><div></div></div></div>
</div>
</a>
)
if (data != null && data.exists == false) return (
<a className={styles.card}>
<h2>AD</h2>
<p>Exists: {redCircle} </p>
<p>Removed:{redCircle}</p>
</a>
)
if (isLoading) return (
<a className={styles.card}>
<h2>AD</h2>
<div className={styles.parent}>
<p id="adstatus" name="adstatus" className={styles.child}>Exists:</p>
<div id="adloader"><div className={styles.loader}><div></div><div></div><div></div></div></div>
</div>
<p>Removed:{redCircle}</p>
</a>
)
}
const router = useRouter()
const [isLoading, setLoading] = useState(true)
useEffect(() => {
if(isLoading && router.isReady){
fetch('../api/decom/ad')
.then(response => response.json())
.then(data => {              
if (data.exists == true) {
Remove()
}else{
setData(data)                
}
setLoading(false)
})
}
}, [isLoading])

如果使用react 18,useEffect钩子将运行两次,这是的预期行为

React 18 introduces a new development-only check to Strict Mode. This new check will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount.

https://reactjs.org/docs/strict-mode.html#ensuring-可重复使用状态

最新更新