我很好奇,如果有一种方法可以将参数传递给中间件而不从状态中检索它。我想要做的是传递一个我们正在使用的通用函数,以确定用户是否已通过身份验证。因此,我不想从代码复制状态中获取认证信息,我想将isAuthenticated
函数传递给中间件。将构造参数传递给redux中间件
我不认为这是在applyMiddleware
框架本地实施,但也许有人有这种情况的工作。
我很好奇,如果有一种方法可以将参数传递给中间件而不从状态中检索它。我想要做的是传递一个我们正在使用的通用函数,以确定用户是否已通过身份验证。因此,我不想从代码复制状态中获取认证信息,我想将isAuthenticated
函数传递给中间件。将构造参数传递给redux中间件
我不认为这是在applyMiddleware
框架本地实施,但也许有人有这种情况的工作。
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));
由于传递给中间件的动作不一定是纯粹的,所以可以传递一个函数作为动作的一部分。由于中间件可以访问商店,并且使用状态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'
}))
)
}
我认为正确的方法是要再次咖喱。在您使用中间件
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
)