• <tfoot id='QEmSG'></tfoot>
    <legend id='QEmSG'><style id='QEmSG'><dir id='QEmSG'><q id='QEmSG'></q></dir></style></legend>

      1. <small id='QEmSG'></small><noframes id='QEmSG'>

      2. <i id='QEmSG'><tr id='QEmSG'><dt id='QEmSG'><q id='QEmSG'><span id='QEmSG'><b id='QEmSG'><form id='QEmSG'><ins id='QEmSG'></ins><ul id='QEmSG'></ul><sub id='QEmSG'></sub></form><legend id='QEmSG'></legend><bdo id='QEmSG'><pre id='QEmSG'><center id='QEmSG'></center></pre></bdo></b><th id='QEmSG'></th></span></q></dt></tr></i><div id='QEmSG'><tfoot id='QEmSG'></tfoot><dl id='QEmSG'><fieldset id='QEmSG'></fieldset></dl></div>

        • <bdo id='QEmSG'></bdo><ul id='QEmSG'></ul>

        多个获取请求中的 setState

        时间:2023-10-02
          <tfoot id='icfJW'></tfoot>

              <tbody id='icfJW'></tbody>

              • <i id='icfJW'><tr id='icfJW'><dt id='icfJW'><q id='icfJW'><span id='icfJW'><b id='icfJW'><form id='icfJW'><ins id='icfJW'></ins><ul id='icfJW'></ul><sub id='icfJW'></sub></form><legend id='icfJW'></legend><bdo id='icfJW'><pre id='icfJW'><center id='icfJW'></center></pre></bdo></b><th id='icfJW'></th></span></q></dt></tr></i><div id='icfJW'><tfoot id='icfJW'></tfoot><dl id='icfJW'><fieldset id='icfJW'></fieldset></dl></div>
              • <legend id='icfJW'><style id='icfJW'><dir id='icfJW'><q id='icfJW'></q></dir></style></legend>

              • <small id='icfJW'></small><noframes id='icfJW'>

                  <bdo id='icfJW'></bdo><ul id='icfJW'></ul>
                • 本文介绍了多个获取请求中的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  上一篇:无法读取未定义 REACT 的属性“地图" 下一篇:理解 js 中的 fetch

                  相关文章

                • <tfoot id='5SNKr'></tfoot>
                  1. <i id='5SNKr'><tr id='5SNKr'><dt id='5SNKr'><q id='5SNKr'><span id='5SNKr'><b id='5SNKr'><form id='5SNKr'><ins id='5SNKr'></ins><ul id='5SNKr'></ul><sub id='5SNKr'></sub></form><legend id='5SNKr'></legend><bdo id='5SNKr'><pre id='5SNKr'><center id='5SNKr'></center></pre></bdo></b><th id='5SNKr'></th></span></q></dt></tr></i><div id='5SNKr'><tfoot id='5SNKr'></tfoot><dl id='5SNKr'><fieldset id='5SNKr'></fieldset></dl></div>

                      • <bdo id='5SNKr'></bdo><ul id='5SNKr'></ul>
                      <legend id='5SNKr'><style id='5SNKr'><dir id='5SNKr'><q id='5SNKr'></q></dir></style></legend>
                    1. <small id='5SNKr'></small><noframes id='5SNKr'>