简体   繁体   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)

 },[]) 
 

The restaurant data in this code is always null. However I have same code in previous screen working perfectly fine.此代码中的餐厅数据始终为 null。但是我在前一个屏幕中使用相同的代码工作得很好。 I dont know why the state is not updating the.我不知道为什么 state 没有更新。 May be useeffect is causing problem可能是 useeffect 导致了问题

To see the changes of restaurantsData you must use an useEffect to verify that change:要查看restaurantsData的更改,您必须使用useEffect来验证该更改:

Like this:像这样:

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