问题描述
我正在为求职面试做 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
fetchApifunction'sPromise.allchain was immediately invokingsetFetched(true)instead of waiting for the chain'sthenableto 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 ) ); };fetchOtherDatafunction is also synchronous and doesn't return a Promise so the outer Promise-chain infetchApidoesn'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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)