我正在尝试编写包含在数组中的所有API。我使用promise all来获取数据,最后我得到了我想要的数据。但是,我有一个问题是将结果存储到Promise.all函数的新数组或对象中。如何在React中的无状态组件上存储来自API的数据。所以这个approch中的期望我可以称之为{dataJSON.title}
import React from 'react'
const ApiComponent = (props) => {
// props.film content
//["https://swapi.co/api/films/2/","https://swapi.co/api/films/6/"]
let dataJSON = []
Promise.all(
props.film.map(url =>
fetch(url)
.then(response => response.json())
.then(
parseJSON => ({
title: parseJSON.title,
episode: parseJSON.episode
})
)
.then(
dataJSON => push[dataJSON]
)
))
return (
// expecting return will call like this
{
dataJSON.title
}
)
}
export default ApiComponent;
如果你的组件是“无状态的”,那么它不应该按照定义存储任何东西,所以最好的办法就是提供像onAjaxComplete这样的处理程序,以便在成功检索结果时调用结果。
const ps = {
films: ["https://swapi.co/api/films/2/","https://swapi.co/api/films/6/"],
onAjaxComplete: (results) => console.log('Here are the results:', results)
};
const ApiComponent = (props) =>
Promise.all(props.films.map(url => fetch(url)
.then(response => response.json())
.then(json => ({
title: json.title,
episode: json.episode_id
}))))
.then(results => props.onAjaxComplete(results));
ApiComponent(ps);
onAjaxComplete prop会采用一个函数来处理结果,当你回来时,如果你正在使用Redux或类似的东西,你可以将结果传递给商店或其他任何东西。
或者,如果您想尝试直接从函数返回已解析的promise值,则you might explore using async/await。但真正的async / await只是语法糖,使得处理异步代码感觉更加迫切。
编辑:正如其他人在上面的评论中提到的,取决于它如何与其他东西集成,你可能会考虑不使这个无状态以避免不必要的请求。或者根本不把它当作一个组件,只需将它作为一个函数,它接受一个要调用的URL列表,以及一个用于处理结果的回调。