You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React报错:Objects are not valid as a React child,Spotify API渲染异常

解决React渲染Spotify API返回内容时的Promise错误

你遇到的错误根源是:getTopTracks是异步函数,直接调用它会返回Promise对象(错误信息里的{_U, _V, _W, _X}就是Promise的内部状态标识),而React无法将Promise当作可渲染的子元素,因此抛出异常。

要正确获取并渲染第一首歌的名称,需要结合React的useState和useEffect钩子处理异步逻辑,修改后的代码如下:

import React, { useState, useEffect } from "react";
import { View, Text } from "react-native"; // 补充导入View和Text组件
import axios from "axios";
import { getSpotifyToken } from "../../hooks/spotifyAuth";

const getTopTracks = async () => {
  const spotifyToken = getSpotifyToken();
  console.log("Getting access Token for TopSongs:", spotifyToken );

  const api_url = "https://api.spotify.com/v1/me/top/tracks?time_range=short_term&limit=5";
  
  try{
    const response = await axios.get(api_url, {
      headers: {
        'Authorization': `Bearer ${spotifyToken}`
      }
    });
    return response.data.items[0].name;
  }catch(error){
    console.log(error);
    return "获取歌曲失败";
  }  
};

const StatsScreen = ({ navigation }) => {
  const [topSong, setTopSong] = useState("加载中...");

  useEffect(() => {
    // 在useEffect内部定义异步函数并调用
    const fetchTopSong = async () => {
      const songName = await getTopTracks();
      setTopSong(songName);
    };
    fetchTopSong();
  }, []); // 空依赖数组确保仅在组件挂载时执行一次

  return (
    <View>
      <Text>StatsScreen</Text>
      <Text>{topSong}</Text>
    </View>
  );
};

export default StatsScreen;

关键修改说明

  • 用useState定义状态变量topSong存储歌曲名称,初始值设为"加载中..."提升体验
  • 用useEffect触发异步请求:避免在组件渲染阶段直接调用异步函数,内部定义异步函数fetchTopSong来获取数据并更新状态
  • 补充导入View和Text组件(原代码遗漏,会导致额外渲染错误)
  • 错误分支返回友好提示,避免状态为空

内容的提问来源于stack exchange,提问作者songexile9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:05:19