我正在构建一个原型,用于在 React 中获取 Spotify 用户的播放列表数据。数据获取在 useEffect 钩子内完成并设置播放列表变量的状态。因此,我想呈现每个播放列表的名称。但是,似乎只有在渲染后才获取数据,从而导致问题,因为在渲染之前未设置状态,因此未定义播放列表变量。如何在继续使用 React 钩子的同时解决这个问题?我的代码如下。
import './App.css'
import queryString from 'query-string'
import React, { useState, useEffect } from 'react'
const App = () => {
const [userData, setUserData] = useState({})
const [accesstoken, setAccesstoken] = useState('')
const [playlists, setPlaylists] = useState({})
useEffect(() => {
let parsed = queryString.parse(window.location.search)
let accesstoken = parsed.access_token
if (!accesstoken) {
return
}
setAccesstoken(accesstoken)
fetch('https://api.spotify.com/v1/me', {
headers: {'Authorization': 'Bearer ' + accesstoken}
}).then(response => response.json())
.then(data => setUserData(data))
fetch(`https://api.spotify.com/v1/me/playlists`, {
headers: {'Authorization': 'Bearer ' + accesstoken}
}).then(response => response.json())
.then(data => setPlaylists(data))
}, [])
return(
<div>
{accesstoken ? (
<div>
<h1>Welcome, {userData.display_name}</h1>
<h2>Playlists</h2>
<div>
{playlists.items.map(playlist =>
<p>
{playlist.name}
</p>
)}
</div>
</div>
) : (
<button onClick={() => window.location = 'http://localhost:8888/login'}>Login</button>
)}
</div>
);
}
export default App;
答案 0 :(得分:0)
使用conditional rendering
。检查渲染中的值
<div>
{userData && <h1>Welcome, {userData.display_name}</h1>}
<h2>Playlists</h2>
{playlists && playlists.items && (
<div>
{playlists.items.map((playlist) => (
<p>{playlist.name}</p>
))}
</div>
)}
</div>;