• <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

        setState in multiple fetch requests(多个获取请求中的 setState)
          <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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  业务场景:使用update语句去更新数据库字段。 原因:update接收值不正确。原来代码: $query = "UPDATE student SET date = now() WHERE id = $id";$result = $mysqli-query($query2) or die($mysqli-error); // 问题出现了在这句 $data = $result-fetch_ass
                  在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会
                  问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转
                  Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)
                  quot;Each child in an array should have a unique key propquot; only on first time render of page(“数组中的每个孩子都应该有一个唯一的 key prop仅在第一次呈现页面时)
                  CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)

                • <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>
                          <tbody id='5SNKr'></tbody>

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