8

我目前正在使用以下服务器端渲染逻辑(使用 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)
      })
  }

我异步获取数据并加载输出以存储页面第一次使用回调加载的时间。

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 方法,有人可以告诉我这是否是一种理想的方法吗?

4

3 回答 3

7

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

我之前通过为每个 API 调用创建一个 Promise 解决了这个问题,并使用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

让我知道是否有任何不清楚的地方。

于 2016-10-25T18:04:00.867 回答
0

您可以尝试express-batch或使用GraphQL是另一种选择。

于 2016-10-30T21:30:37.337 回答
0

您还可以使用 Redux-Sagas 使用纯 Redux 操作来触发多个 api 调用并使用纯操作处理所有这些调用。萨迦简介

于 2016-11-01T02:31:05.837 回答