Reactjs 请求多个get请求的Fetch API
我想知道如何一次获取多个GET URL,然后将获取的JSON数据放入我的React DOM元素中 这是我的密码:Reactjs 请求多个get请求的Fetch API,reactjs,fetch,Reactjs,Fetch,我想知道如何一次获取多个GET URL,然后将获取的JSON数据放入我的React DOM元素中 这是我的密码: fetch(“http://localhost:3000/items/get") .然后(功能(响应){ response.json()。然后( 功能(数据){ ReactDOM.render( , document.getElementById('概述') );} ); }) .catch(函数(err){console.log(err);}); 但是,我希望从服务器中获取额外的
fetch(“http://localhost:3000/items/get")
.然后(功能(响应){
response.json()。然后(
功能(数据){
ReactDOM.render(
,
document.getElementById('概述')
);}
);
})
.catch(函数(err){console.log(err);});
但是,我希望从服务器中获取额外的JSON数据,然后使用传入的所有JSON数据呈现ReactDOM。例如:
ReactDOM.render(
,
document.getElementById('概述')
);
这可能吗?如果没有,还有什么其他解决方案可以将多个JSON数据提取到my rendering ReactDOM元素中?使用一些
Promise的实现。所有()都可以一次发出多个请求,然后对数据执行您想要的操作:
Promise.all([
fetch("http://localhost:3000/items/get1"),
fetch("http://localhost:3000/items/get2"),
fetch("http://localhost:3000/items/get3")
]).then(allResponses => {
const response1 = allResponses[0]
const response2 = allResponses[1]
const response3 = allResponses[2]
...
})
在你下定决心之前,你可以依靠承诺去执行它们。如果您习惯于jQuery,那么也可以使用jQuery承诺
在继续执行代码之前,您将强制执行每个请求都已完成
Promise.all([
取回(“http://localhost:3000/items/get"),
取回(“http://localhost:3000/contactlist/get"),
取回(“http://localhost:3000/itemgroup/get")
])。然后(([项目、联系人列表、项目组])=>{
ReactDOM.render(
,
document.getElementById(“概述”);
);
}).catch((错误)=>{
控制台日志(err);
});
但即使很困难,fetch目前还没有在所有浏览器中实现,因此我强烈建议您创建一个额外的层来处理请求,在那里您可以调用fetch或使用回退,否则,我们可以使用XmlHttpRequest
或jQuery
ajax
除此之外,我强烈建议您查看Redux
,以处理React容器上的数据流。安装将更加复杂,但在将来会有回报
使用async/await更新2018年8月
到目前为止,fetch已经在所有最新版本的主流浏览器中实现,除了IE11之外,包装器仍然很有用,除非您使用polyfill
然后,利用较新的、现在更稳定的javascript特性,如destructuring和async/await,您可能能够使用类似的解决方案来解决相同的问题(请参阅下面的代码)
我相信,尽管乍一看代码似乎多一点,但实际上这是一种更干净的方法。希望能有帮助
试试看{
让[项目、联系人列表、项目组]=等待承诺。全部([
取回(“http://localhost:3000/items/get"),
取回(“http://localhost:3000/contactlist/get"),
取回(“http://localhost:3000/itemgroup/get")
]);
ReactDOM.render(
,
document.getElementById(“概述”);
);
}
捕捉(错误){
控制台日志(err);
};
我需要json格式的响应,所以我自己添加了一点代码
Promise.all([
fetch(url1).then(value => value.json()),
fetch(url2).then(value => value.json())
])
.then((value) => {
console.log(value)
//json response
})
.catch((err) => {
console.log(err);
});
以下是我如何获取多个端点的示例,这可能会对某人有所帮助
const findAnyName = async() => {
const urls = ['https://randomuser.me/api/', 'https://randomuser.me/api/'];
try{
let res = await Promise.all(urls.map(e => fetch(e)))
let resJson = await Promise.all(res.map(e => e.json()))
resJson = resJson.map(e => e.results[0].name.first)
console.log(resJson)
}catch(err) {
console.log(err)
}
}
findAnyName()
或尝试以下操作:将所有URL声明为数组。我们将对此进行循环
数组,并将单个URL引用为数组索引
constructor(props) {
super(props);
this.state = { World: [], Afghanistan: [], USA: [], Australia: [] };
}
const urls = [
'https://corona.lmao.ninja/v2/all',
'https://corona.lmao.ninja/v2/countries/afghanistan',
'https://corona.lmao.ninja/v2/countries/usa',
'https://corona.lmao.ninja/v2/countries/australia'
];
Promise.all(urls.map(url =>
fetch(url)
.then(checkStatus) // check the response of our APIs
.then(parseJSON) // parse it to Json
.catch(error => console.log('There was a problem!', error))
))
.then(data => {
// assign to requested URL as define in array with array index.
const data_world = data[0];
const data_af = data[1];
const data_usa = data[2];
const data_aus = data[3];
this.setState({
World: data_world,
Afghanistan: data_af,
USA: data_usa,
Australia: data_aus
})
})
function checkStatus(response) {
if (response.ok) {
return Promise.resolve(response);
} else {
return Promise.reject(new Error(response.statusText));
}
}
function parseJSON(response) {
return response.json();
}
结果
const { World, Afghanistan, USA, Australia} = this.state;
console.log(World, Afghanistan, USA, Australia)
FYI fetch polyfills的可能副本易于集成,以支持尚未在本机上实现它的浏览器: