我刚刚遇到这个问题,无法准确找到有关我的案例的任何资源。我正在构建一个使用 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)})
}
Run Code Online (Sandbox Code Playgroud)
代码片段运行良好并停止执行
但是当调用“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)})
}
Run Code Online (Sandbox Code Playgroud)
这是整个组件供参考:
import { Box } from "@mui/material";
import React, { useEffect, useState } from "react";
import { useSelector } …Run Code Online (Sandbox Code Playgroud)