Redux thunk,将其用作列表或对象之间的区别

Redux thunk, difference between using it as a list or as an object

我正在阅读我在 GitHub 上找到的一个 React 项目的代码,我发现了 redux thunk 的不同用法,通过查看 GitHub 的官方文档,他们是这样使用它的:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

但在代码中我发现那个人使用了:

import { AsyncStorage } from 'react-native';
import { applyMiddleware, createStore } from 'redux';
import { autoRehydrate, persistStore } from 'redux-persist'
import thunk from 'redux-thunk';
import reducers from '../reducers';

const middleWare = [thunk];

const createStoreWithMiddleware = applyMiddleware(...middleWare)(createStore);

export default configureStore = (onComplete) => {
  const store = autoRehydrate()(createStoreWithMiddleware)(reducers);
  persistStore(store, { storage: AsyncStorage }, onComplete);

  return store;
};

将它用作列表和对象有什么区别?

我们来看看函数签名(source):

function applyMiddleware(...middlewares) { /* logic */ }

applyMiddleware 使用 rest parameter syntax 允许将不定数量的参数 表示为数组 .

正因为如此,两者

applyMiddleware(thunk, otherMiddleware);

const middlewares = [thunk, otherMiddleware];
applyMiddleware(...middlewares);

同样有效。