React Redux:如何找到Redux中调用的最后一个动作并再次触发相同的动作

时间:2019-09-15 02:50:42

标签: reactjs redux react-redux

我在多个地方单击时执行不同的动作。

我想找到已执行的最新操作,然后仅使用“续订”按钮再次执行它。

我该如何寻找最后一个叫的动作? 它必须在redux系统中的某个位置。我只需要知道如何找到它。

1 个答案:

答案 0 :(得分:0)

  

我该如何寻找最后一个叫的动作?它必须在redux系统中的某个地方。

我不知道redux会保存过去的操作的任何地方。但是您可以创建一个custom middleware来拦截并保存操作。像这样:

let lastAction = null;
export const getLastAction = () => lastAction;

export const lastActionMiddleware = store => next => action => {
 lastAction = action;
 return next(action);
}

// In another file, initialize your store with the middleware
// Your code may look different here if you already have middlewares:

import { createStore, applyMiddleware } from 'redux';
import { lastActionMiddleware } from 'whatever/the/path/is';

const store = createStore(
  rootReducer, 
  rootState, 
  applyMiddleware(lastActionMIddleware)
)

// And in yet another file, you can look up the most recent action

import { getLastAction } from 'whatever/the/path/is';

// ...

componentDidMount() {
  const lastAction = getLastAction();
  console.log('the last thing dispatched anywhere was:', lastAction)
}