react-redux:在 componentDidMount 上并行调用多个 api

react-redux: Call multiple apis parallely on componentDidMount

我需要并行调用两个 API。这很重要,因为我想将 page to load 的时间保持在最低限度。

  1. 如果我在componentDidMount中调用两个api(如下所示)那么它是否是异步的。

class Test extends Component{
  constructor(args) {
            super(args)
            this.state = {
               ...
            };
            ...
        }

        componentDidMount() {
            //api1() and api2() are like .get(url).then()
            this.props.dispatch(actions.api1())     
            this.props.dispatch(actions.api2())
        }
    }

对 api1() 和 api2() 的调用将并行还是同步完成?我该如何并行执行


  1. 我还想提一下,我的应用程序使用 redux-thunk 类似下面的东西,但我不确定这段代码到底在做什么。我读过 https://redux.js.org/api-reference/applymiddleware 通过应用中间件我们可以使 dispatch 异步工作。

import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import { createLogger } from 'redux-logger'
import axios from 'axios'
import { routerMiddleware } from 'react-router-redux'

import InitialState from './InitialState'


const middleware = [ thunk.withExtraArgument(axios), routerMiddleware(history) ]

/* eslint-enable no-undef */

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

const store = createStore(
    rootReducer,
    InitialState,
    composeEnhancers(applyMiddleware(...middleware))
)

export default store

Would call to api1() and api2() will be done in parallel or synchronously? And how can I do that parallel?

它们将并行完成。

I have read https://redux.js.org/api-reference/applymiddleware that by applying middleware we can make dispatch work asynchronously.

是的,你是对的。默认情况下,redux 无法处理异步操作,因此您应该考虑使用像 redux-thunksaga.

这样的中间件

默认情况下 Reudx 库中的调度方法是绝对同步的。 您可以使用带有 thunk(或类似 enhancers)的 redux 来消除调度的同步性质,您的调度事件将在调用时包装在 Promise 中 thunks.

此外,与 React / Redux 无关:

浏览器限制了 HTTP 规范中定义的每个域的同时请求数(RFC2616). Check this link 查看每个浏览器系列/版本的最大同时连接数。

您可以在下面看到某些浏览器同时连接到同一域的最大数量。

+---------+-------------+
| Browser | Connections |
+---------+-------------+
| IE 8, 9 |           6 |
| IE 10   |           8 |
| IE 11   |          13 |
| Chrome  |           6 |
| Safari  |           6 |
| Opera   |           6 |
+---------+-------------+

很高兴知道:主线程上的同步 http 请求 由于对用户体验的负面影响已被弃用 XMLHttpRequest Doc.

希望对您有所帮助。