Redux/RTK:为一个切片创建增强器? [英] Redux / RTK: create enhancer for one slice?

查看:36
本文介绍了Redux/RTK:为一个切片创建增强器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Redux/RTK 存储中的一个切片中,我需要做的就是使用 createEntityAdapter() 并导出 setAll CRUD 函数.到目前为止,如此简单 - 感谢 RTK :-)

In one of the slices in my Redux / RTK store, all I need to to do to make the slice do its job is to create an entity adapter using createEntityAdapter() and export the setAll CRUD function. So far, so simple - thanks to RTK :-)

然而,当那个切片的数据进来时,我需要增强"它(或增强"它,如 Redux 文档 调用它),即添加从传入数据派生的更多信息,例如用于在 UI 中显示的格式化数据(人为示例).

However, when data for that slice comes in, I need to "augment" it (or "enhance" it, as Redux docs call it), i.e. add further information derived from data coming in, for example for formatted data displayde in the UI (contrived example).

我为此创建了一个增强器,目标是应用程序可以依赖该切片中的数据在添加后立即完成,即从一开始就包含应用程序组件所需的任何数据.(这来自之前使用非 UI 组件的不成功方法,该组件侦听存储更新并随后增强切片数据 - 这会导致更新/计时问题.)

I created an enhancer for that purpose with the goal that the application can rely on data in that slice being complete as soon as it is added, i.e. containing any data required by the components of the app from the very start. (This comes from a previous, unsuccessful approach using a non-UI component that listened to store updates and enhanced slice data afterwards - which lead to update / timing issues.)

在增强器中,我拦截感兴趣的操作并在将其添加到商店之前修改有效负载(在下面的示例代码中,我只记录操作,但您明白了...):

In the enhancer, I intercept the action that's of interest and modify the payload before it's added to the store (in the sample code below, I'm only logging the action, but you get the idea...):

export const mySliceEnhancer = (createStore) => {
  return (rootReducer, preloadedState, enhancers) => {
    const store = createStore(rootReducer, preloadedState, enhancers)

    function newDispatch(action) {
      // intercept only actions related to my slice
      if (action.type === 'mySlice/setAll') {
        console.debug('mySliceEnhancer > newDispatch > action.payload:\n' +
                        JSON.stringify(action.payload, null, 2));
      }

      const result = store.dispatch(action);
      return result;
    }

    return { ...store, dispatch: newDispatch }
  }
}

这有效,但全局应用于整个商店,即 dispatch 被覆盖";用我的自定义版本任何 发送到商店.这让我担心,因为例如我失去了 跟踪功能 在 Redux Dev Extension 中:对于任何 dispatch,都会显示我的增强器中的那个,无论它是否真的改变了任何东西.

This works, but is applied globally to the entire store, i.e. dispatch is "overwritten" with my custom version for any dispatch to the store. This concerns me because for example I lose trace functionality in the Redux Dev Extension: For any dispatch, the one in my enhancer is shown, no matter if it actually changed anything or not.

问:有没有办法只对 redux 存储的一个切片应用增强器?

Q: Is there any way to apply an enhancer to only one slice of the redux store ?

或者 - 更广泛地询问 - 我的方法是否是一个好主意?

Or - asking more generally - is my approach a good idea at all ?

推荐答案

我认为这是对增强器的用途的误解.

I think this is a misunderstanding of what enhancers are meant to be used for.

首先,增强器总是包装整个 store 对象,并且有能力提供他们自己版本的 store 方法,比如 dispatch.

First, enhancers always wrap the entire store object, and have the ability to supply their own versions of store methods like dispatch.

其次,切片减速器"是一个与商店级代码本身无关的概念.请记住,您实际上只有 一个 减速器 - 您传递给 configureStore 的根减速器.根reducer如何选择在内部拆分工作对商店的其余部分无关紧要 - 它可能是一个巨大的函数,带有一系列处理整个状态树的if语句一次,或使用 combineReducers 按顶级键拆分工作.

Second, "slice reducers" are a concept that is irrelevant to the store-level code itself. Remember that you really only have one reducer - the root reducer that you passed to configureStore. How that root reducer then chooses to split up the work internally doesn't matter to the rest of the store - it could be one giant function with a big series of if statements that deal with the entire state tree at once, or use combineReducers to split up the work by top-level keys.

第三,如果您已正确配置商店,则使用增强器不应消除跟踪功能.根据文档,您可以使用 compose() 来组合多个增强器.如果您使用 RTK 的 configureStore,您可以传递一个 enhancers 数组,它会负责将它们与 DevTools 增强器正确组合在一起.

Third, using an enhancer shouldn't wipe out trace functionality if you've configured the store correctly. Per the docs, you can use compose() to combine multiple enhancers. If you're using RTK's configureStore, you can pass an enhancers array and it will take care of composing them together with the DevTools enhancer correctly.

最后,由于您真正要做的只是查找特定操作并修改其内容,因此您不需要增强器.中间件可以很好地做到这一点:

Finally, since all you're really doing is looking for a specific action and modifying its contents, you don't need an enhancer. A middleware will do this just fine:

const myCustomMiddleware = storeAPI => next => action => {
  if (action.type === 'mySlice/setAll') {
    const state = storeAPI.getState();
    action.payload.someField = state.someValue;
  }

  return next(action);
}

const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(myCustomMiddleware);
})

这篇关于Redux/RTK:为一个切片创建增强器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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