对Redux中派生状态变化的响应

huangapple go评论37阅读模式
英文:

Reacting to changes in derived state with redux

问题

我正在一个相当复杂的项目中使用Redux。它有许多复杂的action creators、reducers和selectors。如果某些经过selectors计算的派生状态发生变化,我需要触发某个特定的action。

实现的天真方式是遍历所有可能会更改它的action creators,并在那里插入触发器。然而,这是不好的,因为这会产生很多重复的代码,而且不能防止在将来添加某些可能更改派生状态而没有这个触发器的action。

以前,这是通过React的useEffect实现的,它将所有派生状态作为依赖项。这是一种非常干净和有效的方式来响应状态的变化。然而,现在我需要将这个逻辑转移到仅使用Redux的情况下。

有什么好的方法来实现这一点?

英文:

I'm using redux at a pretty complicated project. It has a lot of complicated action creators, reducers and selectors. I need to trigger a certain action if some derived state, which is computed via selectors, changes.

The naive way of implementing it would be to go through all the action creators that could change it and insert triggers there. However, it's bad because it's a lot of repetitive code and it doesn't safeguard from adding some action in the future that can change that derived state without this trigger.

Previously, this was achieved via React useEffect which had all derived state as dependencies. It was a very clean and effective way of reacting to changes in state. However, now I need to move this logic to be redux-only.

What would be a good way to achieve this?

答案1

得分: 3

这听起来是 Redux Toolkit 中的 "listener" 中间件的一个出色用例,它专门具有在特定操作类型和基于状态条件的响应中运行反应式逻辑的能力。一个基本示例:

listenerMiddleware.startListening({
  predicate: (action, currentState, previousState) => {
    // 每当此字段更改时触发逻辑
    return currentState.counter.value !== previousState.counter.value
  },
  effect: (action, listenerApi) => {
    // 在这里运行任意同步或异步逻辑,
    // 包括分发操作、读取状态等等
  }
})

请查看Redux文档和这些文章以获取更多详细信息:

英文:

That sounds like an excellent use case for the Redux Toolkit "listener" middleware, which specifically has the ability to run reactive logic in response to both specific action types, and state-based conditions. A basic example

listenerMiddleware.startListening({
  predicate: (action, currentState, previousState) => {
    // Trigger logic whenever this field changes
    return currentState.counter.value !== previousState.counter.value
  },
  effect: (action, listenerApi) => {
    // run arbitrary sync or async logic here, 
    // including dispatching actions, reading state, and much more
  }
})

See the Redux docs and these articles for more details:

huangapple
  • 本文由 发表于 2023年2月6日 06:39:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定