What difference between using `compose` for middleware or list them in `applyMiddleware`

落花浮王杯 提交于 2021-02-08 12:05:05

问题


What the difference between these configureStore functions and where has gone initialState argument?

import { createStore, applyMiddleware } from 'redux';
import logger                           from 'redux-logger';
import thunk                            from 'redux-thunk';

import rootReducer                      from '../reducers';

export default function configureStore(initialState){
   const store = createStore(
        rootReducer,
        initialState,
        applyMiddleware(thunk, logger) //list of middlewares in arguments
    );
    return store;
}

export default function configureStore() {
    const store = compose( //composed middlewares
        applyMiddleware(thunk),
        applyMiddleware(logger)
    )(createStore)(rootReducer);
    return store;
}

回答1:


From the documentation:

All compose does is let you write deeply nested function transformations without the rightward drift of the code. Don't give it too much credit!

and it's usage:

This is a functional programming utility, and is included in Redux as a convenience. You might want to use it to apply several store enhancers in a row.

So in essence, it is a helpful utility if you want to apply a bunch of middleware:

 ...
 compose(
    applyMiddleware(thunk),
    DevTools.instrument(),
    // ... more enhancements, that may or may not be middleware
 )
 ...

applyMiddleware is specifically for wrapping the store's dispatch function, whereas compose will allow you to add additional enhancers that may not have anything to do with dispatch, such as Redux Dev Tools.

Middleware only wraps the store's dispatch function. Technically, anything a middleware can do, you can do manually by wrapping every dispatch call, but it's easier to manage this in a single place and define action transformations on the scale of the whole project.



来源:https://stackoverflow.com/questions/45507365/what-difference-between-using-compose-for-middleware-or-list-them-in-applymid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!