[英]Can't set state in React using hooks
I'm working on a fairly simple app to learn React Hooks and I got stuck.我正在开发一个相当简单的应用程序来学习 React Hooks,但我被卡住了。 I want to fetch and display data from specific Spotify playlist.
我想从特定的 Spotify 播放列表中获取和显示数据。 So far, this is my component:
到目前为止,这是我的组件:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function SongsList() {
const [data, setData] = useState({ songs: [] });
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
const result = await axios.get('https://api.spotify.com/v1/playlists/37i9dQZEVXbMDoHDwVN2tF/tracks', {
headers: {
Authorization: 'Bearer sometoken'
}
}
)
setData(result.data.items);
console.log(result.data.items);
setIsLoading(false);
}
fetchData();
}, [])
return (
<div>
{isLoading ? (
<div>Loading...</div>
) : (
<div>
{data.songs.map(song => (
<li key={song.track.id}>
<p>{song.track.artist}</p>
</li>
))}
</div>
)
}
</div>
)
}
export default SongsList;
This code throws an error saying TypeError: data.songs is undefined
and I can't understand why is that.此代码引发错误,指出
TypeError: data.songs is undefined
,我不明白为什么会这样。 Please note that in my fetchData
function I have a log from my console tu ensure that I at least fetch any data: console.log(result.data.items);
请注意,在我的
fetchData
函数中,我有来自控制台的日志,确保我至少获取任何数据: console.log(result.data.items);
. . It gives me the correct output:
它给了我正确的输出:
But my data
in useState
output seems to be never setted or setted wrong.但是我在
useState
输出中的data
似乎从未设置或设置错误。 Can you please help me to understand what is wrong about my code?你能帮我理解我的代码有什么问题吗? Thanks in advance!
提前致谢!
You are not setting the data
right way.您没有以正确的方式设置
data
。 You have declared data
as an object which contains songs
.您已将
data
声明为包含songs
的对象。 You should set songs
like:您应该设置如下
songs
:
setData({ songs: result.data.items });
And this will work for you.这对你有用。
Considering that your component is mounted before the request is made, you should also check for the presence of the data before rendering.考虑到您的组件是在发出请求之前安装的,您还应该在渲染之前检查数据是否存在。 like below:
像下面这样:
{ data && data.songs.map(song => (
<li key={song.track.id}>
<p>{song.track.artist}</p>
</li>
))
}
Change to this setData({songs: result.data.items});
更改为此
setData({songs: result.data.items});
Because you are defining your songs
array in object.因为您正在对象中定义您的
songs
数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.