我一直在玩星球大战API,我很难从角色(https://swapi.dev/api/people/1/)那里获得电影数据。
导出const SwapiFilms = (props) => { const薄膜,setFilms = useState([]);const filmList = props.filmsUrl;useEffect(() => { function ()){ try { const response = Promise.all( filmList.map(Url) => fetch(url).then((res) => res.json( );console.log(响应);setFilms(响应);} catch (错误){console.log(错误);} getData();},[];返回( <>标题:{films.title}导演:{films.director} {JSON.stringify(薄膜)} );};
发布于 2020-11-09 21:49:33
你应该await Promise.all。
useEffect(() => {
async function getData() { // <-- declare getData an async function
try {
const response = await Promise.all( // <-- await promise resolution
filmList.map((url) =>
fetch(url).then((res) => res.json())
)
);
console.log(response);
setFilms(response);
} catch (error) {
console.log(error);
}
}
getData();
}, []);您可能也不应该将诺言链接和异步/等待混为一谈。坚持一个或另一个
承诺链
useEffect(() => {
Promise.all(filmList.map(fetch))
.then(responses => {
if (!response.ok) {
throw Error('Film response not ok!');
}
return response.json();
})
.then(films => {
console.log(films);
setFilms(films);
})
.catch(error => console.log(error));
}, []);异步/等待
useEffect(() => {
async function getData() {
try {
const responses = await Promise.all(filmList.map(fetch));
const films = await Promise.all(responses.map(res => res.json());
console.log(films);
setFilms(films);
} catch (error) {
console.log(error);
}
}
getData();
}, []);Side __:您的电影状态是一个数组,因此您需要在呈现返回中使用数组方法访问films。
https://stackoverflow.com/questions/64759464
复制相似问题