带有异步 Promise 的 React.js 映射循环是无限的,如果周围的 Promise.all.then(response ... ) 分配响应值
P粉895187266
P粉895187266 2023-09-14 16:02:55
0
1
245

我刚刚遇到这个问题,找不到任何关于我的案例的资源。 我正在构建一个使用 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>)
}

感谢您提前提供的任何帮助,希望我们能解决这个问题!

P粉895187266
P粉895187266

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!