我想知道如何一次获取多个GET URL,然后将获取的JSON数据放入我的React DOM元素中.
这是我的代码:
fetch("http://localhost:3000/items/get")
.then(function(response){
response.json().then(
function(data){
ReactDOM.render(
<Test items={data}/>,
document.getElementById('overview')
);}
);
})
.catch(function(err){console.log(err);});
Run Code Online (Sandbox Code Playgroud)
但是,我想从我的服务器获取额外的JSON数据,然后渲染我的ReactDOM,并将所有这些JSON数据传递给它.例如:
ReactDOM.render(
<Test items={data} contactlist={data2} itemgroup={data3}/>,
document.getElementById('overview')
);
Run Code Online (Sandbox Code Playgroud)
这可能吗?如果没有,那么将多个JSON数据提取到渲染ReactDOM元素的其他解决方案是什么?
rda*_*rte 29
您可以依赖Promise在您解决之前执行它们.如果你习惯了jQuery,你也可以使用jQuery Promises.
使用Promise.all,您将强制执行每个请求,然后再继续执行代码
Promise.all([
fetch("http://localhost:3000/items/get"),
fetch("http://localhost:3000/contactlist/get"),
fetch("http://localhost:3000/itemgroup/get")
]).then(([items, contactlist, itemgroup]) => {
ReactDOM.render(
<Test items={items} contactlist={contactlist} itemgroup={itemgroup} />,
document.getElementById('overview');
);
}).catch((err) => {
console.log(err);
});
Run Code Online (Sandbox Code Playgroud)
但即使是艰难的,fetch也没有在今天的所有浏览器中实现,所以我强烈建议你创建一个额外的层来处理请求,在那里你可以调用fetch或者使用后备,否则,XmlHttpRequest或者说jQueryajax.
除此之外,我强烈建议您查看ReduxReact Containers上的数据流.设置会更复杂,但将来会有所回报.
截至今天,fetch现已在所有主流浏览器的最新版本中实现,除IE11外,包装器仍然有用,除非你使用polyfill.
然后,利用更新和现在更稳定的javascript功能,如解构和异步/等待,您可能能够使用类似的解决方案来解决同样的问题(请参阅下面的代码).
我相信即使乍一看似乎更多的代码,实际上是一种更清洁的方法.希望能帮助到你.
try {
let [items, contactlist, itemgroup] = await Promise.all([
fetch("http://localhost:3000/items/get"),
fetch("http://localhost:3000/contactlist/get"),
fetch("http://localhost:3000/itemgroup/get")
]);
ReactDOM.render(
<Test items={items} contactlist={contactlist} itemgroup={itemgroup} />,
document.getElementById('overview');
);
}
catch(err) {
console.log(err);
};
Run Code Online (Sandbox Code Playgroud)
使用Promise.all(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)的某种实现一次发出多个请求,然后对数据进行所需的处理:
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]
...
})
Run Code Online (Sandbox Code Playgroud)
我需要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);
});
Run Code Online (Sandbox Code Playgroud)
以下是我如何获取多个端点作为示例,这可能会对某人有所帮助
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()
Run Code Online (Sandbox Code Playgroud)
或者试试这个:将所有的 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();
}
Run Code Online (Sandbox Code Playgroud)
结果
const { World, Afghanistan, USA, Australia} = this.state;
console.log(World, Afghanistan, USA, Australia)
Run Code Online (Sandbox Code Playgroud)