React Native useEffect从Axios返回未定义的值

时间:2020-06-07 13:49:17

标签: react-native axios react-hooks use-effect use-state

我试图在API上获取数据,当我第一次console.log时,我仍然获取数据。但是,当我尝试将其设置为我的状态时,它返回未定义的状态。我的代码有什么问题?

```

    useEffect(()=>{
    axios.get(`https://angga605090.herokuapp.com/homeicon`)
      .then(res => {
          console.log(res.data)
          setHomeIcon(res.data)
          console.log(homeicon)
      }).catch((err)=>{
          console.log(err)
      })
},[])


const [homeicon,setHomeIcon]=useState()

```

当我控制台时。日志中,我的数据如下所示:

[{"id": 1, "img": "https://titan.email/wp-content/uploads/2019/12/email-introduction.png", "name": "Memperkenalkan Diri"}, {"id": 2, "img": "https://cdn.wpforms.com/wp-content/uploads/2017/04/thank-you-page-examples.jpg", "name": "Mengucapkan Terima Kasih"}, {"id": 3, "img": "https://media.lifehack.org/wp-content/files/2018/03/27233542/powerful-daily-routine.001-370x208@2x.jpeg", "name": "Kegiatan Sehari-hari"}, {"id": 4, "img": "https://www.goodnewsfromindonesia.id/uploads/post/large-maxresdefault-6-b21cac43d55730ce33a5e9d52af656dd.jpg", "name": "Pengenalan Angka"}, {"id": 5, "img": "https://s3.amazonaws.com/southfloridareporter/wp-content/uploads/2016/04/17080327/days-of-the-year-logo.jpg", "name": "Pengenalan Hari"}]

1 个答案:

答案 0 :(得分:0)

使用状态是异步的,因此无法立即看到更改。

请参阅:useState set method not reflecting change immediately

您可以执行以下操作以查看状态更改:

useEffect(()=>{
    axios.get(`https://angga605090.herokuapp.com/homeicon`)
      .then(res => {
          console.log(res.data)
          setHomeIcon(res.data)
          // console.log(homeicon) <-- remove that line
      }).catch((err)=>{
          console.log(err)
      })
},[])

useEffect(() => {   <-- add this hook
  console.log(homeicon);
},[homeicon])