多个获取请求中的 setState

2023-10-02前端开发问题
4

本文介绍了多个获取请求中的 setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在为求职面试做 StarWars API 任务.

我的代码看起来像这样,我不知道 setCharacters 钩子应该在什么位置.首先呈现页面,然后设置状态.我需要在所有提取完成后呈现页面.

为了提高效率,我将之前的提取更改为 Promise.all() 但现在我被 setCharacters 放置所困.之前的话题可以看这里

I'am doing the StarWars API task for the job interview.

my code look like that and I don't know in what place the setCharacters hook should be. First the page is rendered and then the state is set. I need the page to be rendered when all the fetches are done.

To try to be more efficient i changed the previous fetches into Promise.all() but right now I'am stuck with the setCharacters placement. The previous topic can be seen here useEffect efficiency in Star Wars API


const api = `https://swapi.dev/api/people/`;
    const [characters, setCharacters] = useState([]);
    const [fetched, setFetched] = useState(false);

    useEffect(() => {
        const fetchOtherData = (characters) => {
            const charactersWithAllData = [];
            characters.forEach((character) => {
                const homeworld = character.homeworld;
                const species = character.species;
                const vehicles = character.vehicles;
                const starships = character.starships;
                let urls = [homeworld, ...species, ...vehicles, ...starships];

                Promise.all(
                    urls.map((url) => {
                        if (url.length) {
                            fetch(url)
                                .then((response) => response.json())
                                .then((data) => {
                                    if (url.search("species") > 0) {
                                        character.species = data.name;
                                    }
                                    if (url.search("planets") > 0) {
                                        character.homeworld = data.name;
                                    }
                                    if (url.search("vehicles") > 0) {
                                        character.vehicles.shift();
                                        character.vehicles.push(data.name);
                                    }
                                    if (url.search("starships") > 0) {
                                        character.starships.shift();
                                        character.starships.push(data.name);
                                    }
                                })
                                .catch((err) => console.error(err));
                        }
                        if (!url.length) {
                            if (url.search("species")) {
                                character.species = "Unspecified";
                            }
                            if (url.search("vehicles")) {
                                character.vehicles = "";
                            }
                            if (url.search("starships")) {
                                character.starships = "";
                            }
                        }
                    })
                ).then(charactersWithAllData.push(character));
            });
            setCharacters(charactersWithAllData);
        };

        const fetchApi = () => {
            const characters = [];
            Promise.all(
                [api].map((api) =>
                    fetch(api)
                        .then((response) => response.json())
                        .then((data) => characters.push(...data.results))
                        .then((data) => fetchOtherData(characters))
                        .then(setFetched(true))
                )
            );
        };
        fetchApi();
    }, []);

Thanks for all the of the possible replies.

解决方案

Issue

Found a few issues:

  1. Primary Issue: The fetchApi function's Promise.all chain was immediately invoking setFetched(true) instead of waiting for the chain's thenable to invoke it. This is why you are seeing the empty table before the data has been fetched and processed.

    const fetchApi = () => {
      const characters = [];
      Promise.all(
        [api].map((api) =>
          fetch(api)
            .then((response) => response.json())
            .then((data) => characters.push(...data.results))
            .then((data) => fetchOtherData(characters))
            .then(setFetched(true)) // <-- immediately invoked
        )
      );
    };
    

  2. fetchOtherData function is also synchronous and doesn't return a Promise so the outer Promise-chain in fetchApi doesn't wait for the processing to complete, this is why you still see URL strings instead of the resolved values from the fetch.

Solution

Fix the Promise chain in fetchApi to be invoked in the .then callback. Rework the logic in fetchOtherData to wait for the additional fetch requests to resolve.

Here's my suggested solution:

const api = `https://swapi.dev/api/people/`;

function App() {
  const basicClassName = "starWarsApi";
  const [characters, setCharacters] = useState([]);
  const [fetched, setFetched] = useState(false);

  useEffect(() => {
    const fetchOtherData = async (characters) => {
      const characterReqs = characters.map(async (character) => {
        const { homeworld, species, starships, vehicles } = character;
        const urls = [homeworld, ...species, ...vehicles, ...starships];

        // Make shallow copy to mutate
        const characterWithAllData = { ...character };

        const urlReqs = urls.map(async (url) => {
          if (url.length) {
            try {
              const response = await fetch(url);
              const { name } = await response.json();
              if (url.includes("species")) {
                characterWithAllData.species = name;
              }
              if (url.includes("planets")) {
                characterWithAllData.homeworld = name;
              }
              if (url.includes("vehicles")) {
                characterWithAllData.vehicles.shift();
                characterWithAllData.vehicles.push(name);
              }
              if (url.includes("starships")) {
                characterWithAllData.starships.shift();
                characterWithAllData.starships.push(name);
              }
            } catch (err) {
              console.error(err);
            }
          } else {
            if (url.includes("species")) {
              characterWithAllData.species = "Unspecified";
            }
            if (url.includes("vehicles")) {
              characterWithAllData.vehicles = "";
            }
            if (url.includes("starships")) {
              characterWithAllData.starships = "";
            }
          }
        });

        await Promise.all(urlReqs); // <-- wait for mutations/updates
        return characterWithAllData;
      });

      return Promise.all(characterReqs);
    };

    const fetchApi = () => {
      Promise.all(
        [api].map((api) =>
          fetch(api)
            .then((response) => response.json())
            .then((data) => fetchOtherData(data.results))
            .then((charactersWithAllData) => {
              setCharacters(charactersWithAllData);
              setFetched(true);
            })
        )
      );
    };
    fetchApi();
  }, []);

  return (
    <div className={basicClassName}>
      {fetched && (
        <>
          <h1 className={`${basicClassName}__heading`}>Characters</h1>
          <div className={`${basicClassName}__inputsAndBtnsSection`}>
            <FilteringSection
              basicClassName={`${basicClassName}__inputsAndBtnsSection`}
            />
            <ButtonsSection
              basicClassName={`${basicClassName}__inputsAndBtnsSection`}
            />
          </div>
          <CharactersTable characters={characters} />
        </>
      )}
    </div>
  );
}

这篇关于多个获取请求中的 setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Fatal error: Call to a member function fetch_assoc() on a no
业务场景:使用update语句去更新数据库字段。 原因:update接收值不正确。原来代码: $query = "UPDATE student SET date = now() WHERE id = $id";$result = $mysqli-query($query2) or die($mysqli-error); // 问题出现了在这句 $data = $result-fetch_ass...
2024-12-13 前端开发问题
136

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437

layui中table列表 增加属性 edit="date",不生效怎么办?
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11 前端开发问题
455

Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)...
2024-04-20 前端开发问题
5