我想獲取一個“board_ID”:fetch("http://localhost:4000/NewGame") 然后在以下獲取地址中使用該 board_ID:fetch("http://localhost:4000/Turn/ " board_ID)。問題在于 setboard_ID(之前使用 useState 初始化)更新 board_ID 的速度不夠快,因此在獲取“Turn”時出現錯誤。解決這個問題的最佳方法是什么?
useEffect(() => {
if (didFetch == false) {
fetch("http://localhost:4000/NewGame")
.then(res => res.text())
.then(
(result) =>{
console.log(result)
**setboard_ID(result)**
},
(error) => {
setisLoaded(true)
seterror(error)
}
)
}
})
useEffect(() => {
if (getplayer == true){
console.log("http://localhost:4000/Turn/" board_ID)
**fetch("http://localhost:4000/Turn/" board_ID)**
.then(res => res.text())
.then(
(result) =>{
console.log(result)
player = result
setGetplayer(false)
},
(error) => {
seterror(error)
}
)
}
})
uj5u.com熱心網友回復:
您可以嘗試運行依賴于該狀態的 useEffect。像這樣作業:
useEffect(function, [dependency])
然后,第一個 useEffect 將運行并更新啟動第二個的狀態
uj5u.com熱心網友回復:
在依賴陣列 [board_ID] 中添加到第二個 useEffect 中的 board_ID。
useEffect 掛鉤允許您在功能組件中執行副作用。有一個依賴陣列來控制效果何時運行。它在掛載組件時以及在 useEffect 的依賴項發生更改時重新渲染時運行
uj5u.com熱心網友回復:
我不確定為什么你的 useEffects 沒有依賴陣列(這很危險),因為它會重復呼叫生命周期方法,這將重新渲染 UI/App 很多次,因為 App 可能會崩潰。另外,我沒有看到任何檢查是否存在第二個 useEffect 的 board_ID。
在依賴陣列中添加 board_ID 應該可以解決部分問題。
須藤:
useEffect(() => {
if (getplayer && board_ID !='' ){ // == true is redundant and board_ID != <your initial state means it has some valid value>
console.log("http://localhost:4000/Turn/" board_ID)
**fetch("http://localhost:4000/Turn/" board_ID)**
.then(res => res.text())
.then(
(result) =>{
console.log(result)
player = result
setGetplayer(false)
},
(error) => {
seterror(error)
}
)
}
},[board_ID])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/536973.html
標籤:javascript反应
上一篇:Debezium的增量快照
