在 Redux 中访问中间件中的状态 [英] Accessing state in middleware in Redux

查看:32
本文介绍了在 Redux 中访问中间件中的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 React/Redux 应用程序中有一个中间件,如下所示:

I have a middleware in my React/Redux app that looks like this:

export const myMiddleware = (store) => (next) => async (action) => {

   switch (action.type) {
      case types.SOME_ACTION:
      // Some logic here...
      break;
   }
}

我需要访问此处的状态,以便我可以执行该中间件旨在处理的逻辑.

I need to access the state here so that I can execute my logic this middleware is designed to handle.

我想,因为 store 被传递到中间件中,所以我可以访问它,但是当我检查 store 时,我根本看不到状态.我确实看到了一个 getState() 函数,但是当我使用它时,看起来它正在为我提供初始状态,而不是其中包含数据的当前状态.

I thought, because store is being passed into the middleware, I could access it but when I inspect store, I don't see the state at all. I do see a getState() function but when I used it, looks like it's getting me the initial state, not the current state with data in it.

这是我检查时看到的 store 对象:

Here's the store object I see when I inspect it:

这是我的商店以及我如何在其中包含中间件:

Here's my store and how I include the middleware in it:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers/root-reducer';
import { myMiddleware } from '../middleware/my-middleware';

export default function configureStore(initialState) {

    const store = createStore(
        rootReducer,
        initialState,
        applyMiddleware(thunk, myMiddleware)
    );

    return store;
}

如何访问中间件中的状态?

How do I access state in my middleware?

推荐答案

如果您在异步回调中使用 getState(),您可以在中间件中获取更新的状态(在当前操作之后)(例如,signalR 响应).在本例中,我使用 setTimeout() 来模拟异步操作.

You can get the updated state (after the current action) in the middleware, if you use getState() inside an async callback (signalR response for example). In this case, I've used setTimeout() to simulate an async action.

注意:

  1. 虽然这在理论上可行,但这不是一个好主意.不能保证其他操作没有改变状态.在示例中,您可以看到中间件显示了两个已调度操作的结束状态.
  2. 关于评论中的讨论 - 简单的状态更改应该在 reducer 中完成,而不是在中间件中.

const { createStore, applyMiddleware } = Redux;

const DEMO_ACTION = 'DEMO_ACTION';

const demoAction = (payload) => ({
  type: DEMO_ACTION,
  payload
});

const myMiddleware = ({ getState }) => (next) => async (action) => {
  setTimeout( // simulates an async action
    () => console.log(action.payload, getState())
  , 0);
   
  next(action);
}

const initialState = { data: [] };

const rootReducer = (state = initialState, { type, payload }) => {
  switch(type) {
    case DEMO_ACTION:
      return {
        ...state,
        data: [...state.data, payload]
      };
  }
  
  return state;
}

const store = createStore(
  rootReducer,
  applyMiddleware(myMiddleware)
);

store.dispatch(demoAction('data1'));
store.dispatch(demoAction('data2'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.0/redux.min.js"></script>

这篇关于在 Redux 中访问中间件中的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆