我想从多个 url 获取 json 数据并将其显示在前端。 以下是网址:
1) 本地主机:3000/api/getdata1
2) 本地主机:3000/api/getdata2
3) 本地主机:3000/api/getdata3
不要在每个网址上使用.fetch()
,如下所示:
.fetch('localhost:3000/api/getdata1')
.fetch('localhost:3000/api/getdata2')
.fetch('localhost:3000/api/getdata3')
这可以在 ReactJs 中以更有效的方式完成吗?
我正在尝试:
const dataurls = [
'localhost:3000/api/getdata1',
'localhost:3000/api/getdata2',
'localhost:3000/api/getdata3'
];
const promisedurl = dataurls.map(httpGet);
Promise.all(promisedurls)
.then(data=> {
for (const d of data) {
console.log(d);
}
})
.catch(reason => {
// Receives first rejection among the Promises
});
请建议应该使用哪一个,或者是否有任何有效的方法可以从多个网址获取数据。
最佳答案
ReactJS是一个View层库。它与您如何从服务器获取任何数据无关。
即使是 Redux 和 Reflux 等状态库也没有实现任何获取数据的方法。在大多数情况下,您可以在自定义应用程序代码中执行此操作。有时使用额外的库(例如 Redux 中间件)。
所以,是的:你的 Promise.all(<several https requests here>)
是实现这一目标的最自然的方式。
关于javascript - Reactjs 如何从多个 url 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49081729/