有一段时间,我一直在讨论如何在Redux中使用服务器交互(通过ajax)实现undo/redo .
我已经提出了一个使用命令模式的解决方案,其中操作使用execute和undo方法作为命令注册,而不是调度操作您调度命令.然后将命令存储在堆栈中并在需要时引发新操作.
我当前的实现使用中间件拦截调度,测试命令和调用Command的方法,看起来像这样:
let commands = [];
function undoMiddleware({ dispatch, getState }) {
return function (next) {
return function (action) {
if (action instanceof Command) {
// Execute the command
const promise = action.execute(action.value);
commands.push(action);
return promise(dispatch, getState);
} else {
if (action.type === UNDO) {
// Call the previous commands undo method
const command = commands.pop();
const promise = command.undo(command.value);
return promise(dispatch, getState);
} else {
return next(action); …Run Code Online (Sandbox Code Playgroud)