小编Fel*_*est的帖子

带有异步 Promise 的 React.js 映射循环是无限的,如果周围的 Promise.all.then(response ... ) 分配响应值

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

javascript reactjs react-hooks

0
推荐指数
1
解决办法
34
查看次数

标签 统计

javascript ×1

react-hooks ×1

reactjs ×1