Redux Toolkit addListener操作未注册动态中间件

6mw9ycah  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(146)

我尝试用RTK添加一个动态侦听器中间件,但它似乎没有拦截操作。我使用了特殊的addListener操作,根据文档,该操作应该允许从React组件注入动态中间件。在Redux开发工具上,我看到记录了listenerMiddleware/add操作,但之后我看到中间件没有拦截任何操作。

import { addListener} from '@reduxjs/toolkit';
import { useDispatch } from 'react-redux';

const App = () => {
  const dispatch = useDispatch();
  useEffect(() => {
        const unsubscribe = dispatch(
        addListener({
            predicate: () => {
                return true;
            },
            effect: async (action, listenerApi) => {
                console.log('log', action);

            },
        })
    );
    return () => unsubscribe();
}, [])
}
pjngdqdw

pjngdqdw1#

您必须将侦听器添加到您的商店-如果您跳过这一步,中间件也将不会侦听您的商店。
从文档中:

// Create the middleware instance and methods
const listenerMiddleware = createListenerMiddleware()

const store = configureStore({
  reducer: {
    todos: todosReducer,
  },
  // Add the listener middleware to the store.
  // NOTE: Since this can receive actions with functions inside,
  // it should go before the serializability check middleware
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().prepend(listenerMiddleware.middleware),
})

相关问题