setState in multiple fetch requests(多个获取请求中的 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:
Primary Issue: The
fetchApi
function'sPromise.all
chain was immediately invokingsetFetched(true)
instead of waiting for the chain'sthenable
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 ) ); };
fetchOtherData
function is also synchronous and doesn't return a Promise so the outer Promise-chain infetchApi
doesn't wait for the processing to complete, this is why you still see URL strings instead of the resolved values from thefetch
.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多个获取请求中的 setState
基础教程推荐
- Chart.js 在线性图表上拖动点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01