gpt4 book ai didi

javascript - Redux 中间件设计 re : return values

转载 作者:数据小太阳 更新时间:2023-10-29 04:45:25 25 4
gpt4 key购买 nike

所以我刚刚阅读了 redux 中间件,听起来不错。不过有一件事困扰着我——中间件的返回值。

我知道中间件的某些实例会返回一些东西(即 redux-promise),而我得到其他中间件(即 logging)不会 - 只是返回next(action) 的结果。

我的问题是,如果我想使用两个都返回内容的中间件会发生什么——它们肯定会互相破坏,而我只会获得最外层中间件的返回值。

express/connect 中间件通过让中间件将其“结果”写入 reqres 对象来解决这个问题,但是解决方案是什么还原?

编辑

这是我的问题的一个更具体的例子:

我有两个中间件:

  1. 将所有操作延迟 3 秒分派(dispatch)的中间件。这个中间件返回一个函数,可以调用它来取消调度
  2. 返回数字 5 的中间件,因为出于某种原因我需要数字 5。

根据我链接这两个中间件的顺序,我的 dispatch(action) 的结果要么是延迟取消 fn,要么是数字 5。但是我如何获得两者这些结果?

最佳答案

下面是一个可运行的脚本,它演示了我正在尝试(但未能)描述的问题。它还包括一个潜在的解决方案(使用中间件包装器)。很想知道那里是否有更优雅的解决方案....

var { createStore, applyMiddleware } = require( "redux" );
var dispatchResult;

// create the results object to be passed along the middleware chain, collecting
// results as it goes
const genesis = _store => next => action => {
next( action );
return {};
};

const wrapper = ( key, mware ) => store => next => action => {

// extract the results object by storing the result of next(action)
// when it is called within the middleware
var extractedResult;
function modifiedNext( action ) {
extractedResult = next( action );
return extractedResult;
}

// get the result of this middleware and append it to the results object
// then pass on said results object...
var newResult = mware( store )( modifiedNext )( action );
extractedResult[ key ] = newResult;
return extractedResult;
};

// create standard logging middleware
const logger = store => next => action => {
let result = next( action );
console.log( `value is: ${ store.getState() }.`);
return result;
};

// create middleware that returns a number
const gimme = val => _store => next => action => {
next( action );
return val;
};

// create our super simple counter incrementer reduer
function reducer( state = 0, action ) {
if( action.type === "INC" )
return state + 1;
return state;
}


// first lets try running this without the wrapper:
dispatchResult = createStore( reducer, applyMiddleware(
gimme( 4 ),
logger,
gimme( 5 )
) ).dispatch( { type : "INC" } );

// will return only 4 (the result of the outermost middleware)
// we have lost the 5 from the gimme(5) middleware
console.log( dispatchResult );

// now we include the middleware wrapper and genesis middleware
dispatchResult = createStore( reducer, applyMiddleware(
wrapper( "g4", gimme( 4 ) ),
logger,
wrapper( "g5", gimme( 5 ) ),
genesis
) ).dispatch( { type : "INC" } );

// we will now return { g4 : 4, g5 : 5 }
// we have preserved the results of both middlewares
console.log( dispatchResult );

关于javascript - Redux 中间件设计 re : return values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42657447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com