我想知道如何一次获取多个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);});
但是,我想从服务器中获取其他JSON数据,然后使用传递到其中的所有这些JSON数据呈现我的ReactDOM。例如:
ReactDOM.render( <Test items={data} contactlist={data2} itemgroup={data3}/>, document.getElementById('overview') );
这可能吗?如果不是,将多个JSON数据提取到我的渲染ReactDOM元素中的其他解决方案是什么?
您可以在解决方案之前依靠Promises来执行它们。如果您习惯使用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); });
但即使是艰难的,取并不是在所有的浏览器从今天开始实施的,所以我强烈建议你创建一个额外的层来处理请求,也可以拨打获取或使用回退否则,假设XmlHttpRequest或jQueryAJAX。
XmlHttpRequest
jQuery
除此之外,我强烈建议您看一下Redux处理React容器上的数据流。设置会更加复杂,但将来会有所回报。
Redux
到目前为止,fetch现在已在所有最新版本的主流浏览器中实现,但IE11除外,除非您使用polyfill,否则包装器仍然有用。
然后,利用新的和现在更稳定的javascript功能(例如,解构和async / await),您可以针对相同的问题使用类似的解决方案(请参见下面的代码)。
我相信,即使乍一看似乎有些代码,实际上也是一种更清洁的方法。希望能帮助到你。
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); };