首页 > 解决方案 > Redux thunk,将其用作列表或用作对象之间的区别

问题描述

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

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;
};

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

标签: javascriptreact-nativereduxredux-thunk

解决方案


让我们看一下函数签名(source):

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

applyMiddleware使用允许将不定数量的参数表示为数组的其余参数语法

正因为如此,两者

applyMiddleware(thunk, otherMiddleware);

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

同样有效。


推荐阅读