我很好奇是否有办法将参数传递给中间件而不从状态中检索它。我想要做的是传递我们正在使用的通用函数,该函数确定用户是否经过身份验证。因此,我希望将isAuthenticated
函数传递给中间件,而不是从代码重复的状态中检索身份验证信息。
我不认为这是在applyMiddleware
框架中本地实现的,但也许有人可以解决这种情况。
答案 0 :(得分:3)
好的,正确的方法是一个包装函数,它将包装实际的中间件函数
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(middlewareWrapper(args));
答案 1 :(得分: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'
}))
)
}
答案 2 :(得分: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
)