[英]Updating an array with an API response using useState
I'm working in React and want to update an array I have with the response from an API request to the musixmatch API.我在 React 中工作,想用从 API 请求到 musixmatch API 的响应来更新我拥有的数组。 Basically, albums.tracks.gets returns an array of all the songs on a certain album.
基本上,albums.tracks.gets 返回某个专辑中所有歌曲的数组。 This is the res.data response that I'm getting back from the API request I'm trying to basically load this entire album_list 'array' into an array called albums using a useState hook.
这是我从 API 请求返回的 res.data 响应,我正在尝试使用 useState 挂钩将整个专辑列表“数组”基本上加载到名为专辑的数组中。 What is the best approach here?
这里最好的方法是什么? This is the code that I have written to update albums Currently, I'm defining albums as a state and trying to use setAlbums to update it.
这是我为更新专辑而编写的代码目前,我将专辑定义为 state 并尝试使用 setAlbums 对其进行更新。 I am trying to load the entire album_list array and load all of the names/album_ids into the array.
我正在尝试加载整个album_list 数组并将所有名称/album_ids 加载到数组中。 Right now, when I console.log(albums) the console just prints out [], an empty array.
现在,当我console.log(albums)控制台只打印出 [],一个空数组。 Is there a way to store both in some sort of dict?
有没有办法将两者都存储在某种字典中? Or would I have to store one or the other in a simple array.
或者我是否必须将一个或另一个存储在一个简单的数组中。 Thank you!
谢谢!
There is two issues in the second picture, which may lead to the empty array:第二张图有两个问题,可能会导致空数组:
res.data.message.body.album_lis
but adding res.data.message.body.album_list
to your state variable.res.data.message.body.album_lis
但将res.data.message.body.album_list
添加到您的 state 变量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.