[英]Can't able to set the value for useState hook in ReactJS
我使用 axios 訪問“http://localhost:8000/api/lists/”,在訪問它之后,如果我使用 console.log() ,那么這些值將在控制台中打印,但是在設置狀態時它會顯示一個空數組.. 如何將 res.data 的值設置為 setArrData()。 誰能幫忙解決一下?...
const [arrData, setArrData] = React.useState([])
useEffect(()=>
getData()
},[])
const getData=()=>{
let inp=field.inp
axios.post('http://localhost:8000/api/lists/',{
'input':inp
},
{
headers:{'Content-Type': 'application/json'},
}
).then(res=>{
if(res.status===200){
setArrData(res.data)
console.log(arrData)
console.log(res.data)
}
}).catch(err=>console.log(err))
}
因為setState
在asynchronous
,所以在setState
之后你看不到新的狀態。 如果你想看到arrData
的變化,你可以使用useEffect
:
useEffect(() => {
console.log(arrData);
}, [arrData])
任何反應鈎子中的設置器都是異步的。 React 在后台設置狀態並觸發事件以重新渲染組件或任何依賴於該狀態的更改,所有這些都是異步的。
setArrData
設置數據,但要讀取更新的數據,由於上述原因,您應該使用useEffect
鈎子。
useEffect(()=>
console.log(arrData); <-- on first render the value here will be what you have assigned while defining the state i.e. [] in this case.
}, [arrData]) <--- this is dependency array,
that tell this *useEffect* to run when *arrData* state changes
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.