我刚刚遇到这个问题,找不到任何关于我的案例的资源。 我正在构建一个使用 Spotify API 的 React 应用程序,并想要执行一个函数,该函数用“ArtistInformation”数组(一个来自 API 端点的 js 对象)填充本地 useState 对象。
此代码示例循环访问艺术家 id 数组,并且应该仅执行 Api 函数“spotiApi.getArtistInfo(id)”一次。
像这样运行时:
const getArtistInformation = () => {
console.log("sp ids",spotifyArtistIds)
Promise.all(spotifyArtistIds.map(id => {
return spotiApi.getArtistInfo(id)
})).then(respList => {
// setArtistInfo(respList)
console.log("artistInfo", artistInfo)})
}
代码片段运行良好并停止执行
但是当调用“setArtistInfo”useState 时,循环会继续无限执行
const getArtistInformation = () => {
console.log("sp ids",spotifyArtistIds)
Promise.all(spotifyArtistIds.map(id => {
return spotiApi.getArtistInfo(id)
})).then(respList => {
setArtistInfo(respList)
console.log("artistInfo", artistInfo)})
}
以下是整个组件供参考:
import { Box } from "@mui/material";
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import SpotifyApi from "../../api/SpotifyApi";
export const DashboardView = () => {
const spotifyArtistIds = useSelector(state => state.member.spotifyArtistIds)
const [artistInfo, setArtistInfo] = useState([])
const [showId, setShowId] = useState(spotifyArtistIds[0])
const spotiApi = new SpotifyApi();
const getArtistInformation = () => {
console.log("sp ids",spotifyArtistIds)
Promise.all(spotifyArtistIds.map(id => {
return spotiApi.getArtistInfo(id)
})).then(respList => {
// setArtistInfo(respList)
console.log("artistInfo", artistInfo)})
}
const getThisArtistInfo = () => {
console.log("art", artistInfo)
return artistInfo.filter(info => info.data.id === showId)[0].data
}
useEffect(() => {
getArtistInformation()
})
return (
<Box>
<h2>{getThisArtistInfo()?.name}'s Dashboard</h2>
</Box>)
}
感谢您提前提供的任何帮助,希望我们能解决这个问题!
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号
循环不会无休止地执行,组件会无休止地重新渲染。这会导致重新渲染:
这在每次渲染时执行:
useEffect(() => { getArtistInformation(); });因此每次渲染都会获取艺术家信息,从而触发重新渲染,从而获取艺术家信息,从而触发重新渲染,等等
如果目的是仅在第一次渲染上获取艺术家信息,请包含一个空的依赖项数组:
useEffect(() => { getArtistInformation(); }, []); // <-- here