2016-08-15 17 views
4

我很好奇,如果有一種方法可以將參數傳遞給中間件而不從狀態中檢索它。我想要做的是傳遞一個我們正在使用的通用函數,以確定用戶是否已通過身份驗證。因此,我不想從代碼複製狀態中獲取認證信息,我想將isAuthenticated函數傳遞給中間件。將構造參數傳遞給redux中間件

我不認爲這是在applyMiddleware框架本地實施,但也許有人有這種情況的工作。

回答

2

ok了要做到這一點正確的方式被證明是一個包裝的功能,將包裹實際中間件功能

export const middlewareFunction = (store) => (next) => (action) => { 
    do some stuff with something... 
} 

如果這是你的實際的中間件功能,比你應該應用中間件作爲

applyMiddleware(middlewareFunction); 

,你應該做的事情來傳遞參數是實現像

export const middlewareWrapper = (args) => { 
    do some stuff with your args 
    return (state) => (next) => (action) => { 
     do more stuff with your args and actions 
    } 
} 

使用這種語法功能,可以應用中間件爲:

applyMiddleware(middlewareFunction(args)); 
1

由於傳遞給中間件的動作不一定是純粹的,所以可以傳遞一個函數作爲動作的一部分。由於中間件可以訪問商店,並且使用狀態store.getState(),我們可以將該方法應用於狀態,並獲得計算結果。

real world example of redux的API中間件,你可以看到endpoint可以是功能,和實際的端點可以從狀態計算(見星號註釋的代碼):

export default store => next => action => { 
    const callAPI = action[CALL_API] 
    if (typeof callAPI === 'undefined') { 
    return next(action) 
    } 

    let { endpoint } = callAPI 
    const { schema, types } = callAPI 

/***************************************************************************/  
    /** if the endpoint is a function compute the actual endpoint from state ***/ 
    if (typeof endpoint === 'function') { 
    endpoint = endpoint(store.getState()) 
    } 
    /***************************************************************************/ 

    if (typeof endpoint !== 'string') { 
    throw new Error('Specify a string endpoint URL.') 
    } 
    if (!schema) { 
    throw new Error('Specify one of the exported Schemas.') 
    } 
    if (!Array.isArray(types) || types.length !== 3) { 
    throw new Error('Expected an array of three action types.') 
    } 
    if (!types.every(type => typeof type === 'string')) { 
    throw new Error('Expected action types to be strings.') 
    } 

    function actionWith(data) { 
    const finalAction = Object.assign({}, action, data) 
    delete finalAction[CALL_API] 
    return finalAction 
    } 

    const [ requestType, successType, failureType ] = types 
    next(actionWith({ type: requestType })) 

    return callApi(endpoint, schema).then(
    response => next(actionWith({ 
     response, 
     type: successType 
    })), 
    error => next(actionWith({ 
     type: failureType, 
     error: error.message || 'Something bad happened' 
    })) 
) 
} 
0

我認爲正確的方法是要再次咖喱。在您使用中間件

import myMiddleWare from '/myMiddleWare.js' 
import { applyMiddleware } from 'redux' 

args = // whatever arguments you want  
applyMiddleware(myMiddleWare(args)) 

myMiddleWare.js

文件

export default (args) => ({getState, dispatch}) => (next) => (action) => (
    // Use args do your hearts content 
)