簡體   English   中英

React native fetch state 沒有更新?

[英]React native fetch state not updating?

    const [restaurantsData,setrestaurantsData]=useState([])
  useEffect(()=>{
    const getData = async () => {
    await fetch('http://localhost:5000/api/v1/res/')
      .then((response) => response.json())
      .then((json) => {setrestaurantsData(json.data),console.log(restaurantsData)})
      .catch((error) => console.error(error))
      .finally();
  };
getData();
console.log(id)
console.log("photo",restaurantsData.photo)
  },[])

 useEffect(()=>
 {
  for (const {type: t} of menuDetailedData) 
 { 
   routes.push({key:i,title:t})
   i++;
 }
 console.log("routes",routes)
let acc=[]
 for(let i=0; i<menuDetailedData.length-1;i++)
 {
  if(routes[i].title===routes[i+1].title)
  {
    acc.push(routes[i])
  }
}
setroutes(routes.filter(item => !acc.includes(item)))
console.log("acc",acc)

 },[]) 
 

此代碼中的餐廳數據始終為 null。但是我在前一個屏幕中使用相同的代碼工作得很好。 我不知道為什么 state 沒有更新。 可能是 useeffect 導致了問題

要查看restaurantsData的更改,您必須使用useEffect來驗證該更改:

像這樣:

useEffect(()=> {
   console.log(restaurantsData)
   // if the restaurantsDate is still null here probably your service its not working correctly 
   //NOTE: as I am passing the restaurantsData in the dependency array of the useEffect every time that restaurantsData change this will execute.
}, [restaurantsData])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM