如何在服务器端渲染的React应用程序中构造多个HTTP请求?

我目前正在使用下面的服务器端渲染逻辑(使用reactjs + nodejs + redux)第一次同步获取数据,并将其设置为存储中的初始状态。

fetchInitialData.js

export function fetchInitialData(q,callback){ const url='http://....' axios.get(url) .then((response)=>{ callback((response.data)); }).catch((error)=> { console.log(error) }) } 

我asynchronous获取数据,并加载输出存储在第一次使用callback加载页面。

 handleRender(req, res){ fetchInitialData(q,apiResult => { const data=apiResult; const results ={data,fetched:true,fetching:false,queryValue:q} const store = configureStore(results, reduxRouterMiddleware); .... const html = renderToString(component); res.status(200); res.send(html); }) } 

我有一个要求在初始页面加载4到5个API调用,因此想要检查是否有一个简单的方法来实现在页面加载多个调用。

我是否需要链接api调用并手动合并来自不同API调用的响应并将其发回以加载初始状态?

更新1:我想使用axios.all方法,有人可以告诉我,如果这是一个理想的方法?

你想确保请求并行发生,而不是按顺序发生。

我已经通过为每个API调用创buildPromise解决了这个问题,并使用axios.all()等待所有的调用。 下面的代码基本上是伪代码,稍后我可以深入了解更好的实现。

 handleRender(req, res){ fetchInitialData() .then(initialResponse => { return axios.all( buildFirstCallResponse(), buildSecondCallResponse(), buildThirdCallResponse() ) }) .then(allResponses => res.send(renderToString(component))) } buildFirstCallResponse() { return axios.get('https://jsonplaceholder.typicode.com/posts/1') .catch(err => console.error('Something went wrong in the first call', err)) .then(response => response.json()) } 

注意所有的响应如何被捆绑到一个数组中。

Redux文档进入服务器端呈现一点,但你可能已经看到了。 redux.js.org/docs/recipes/ServerRendering

同时检查Promise文档以查看.all() 。 developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

如果有什么不清楚,请告诉我。

您可以尝试快速批处理或与GraphQL是另一种select。

您也可以使用Redux-Sagas来使用纯Redux操作来触发多个API调用,并使用纯操作处理所有这些调用。 萨加斯介绍