gpt4 book ai didi

redux - 如何处理 redux reducer 和 action 中的横切关注点

转载 作者:行者123 更新时间:2023-12-04 16:07:19 25 4
gpt4 key购买 nike

给定一个像这个问题中的用例:

Best way to update related state fields with split reducers?

处理依赖于自身状态之外的状态的 reducer 中的 Action 的最佳实践是什么?上面问题的作者最终只是将整个状态树作为第三个参数传递给每个 reducer 。这似乎是严厉且危险的。 Redux FAQ 列出了以下潜在的解决方案:

  • If a reducer needs to know data from another slice of state, the state tree shape may need to be reorganized so that a single reducer is handling more of the data.
  • You may need to write some custom functions for handling some of these actions. This may require replacing combineReducers with your own top-level reducer function.
  • You can also use a utility such as reduce-reducers to run combineReducers to handle most actions, but also run a more specialized reducer for specific actions that cross state slices.
  • Async action creators such as redux-thunk have access to the entire state through getState(). An action creator can retrieve additional data from the state and put it in an action, so that each reducer has enough information to update its own state slice.


在我的用例中,我有一个“继续”操作,用于确定允许用户在多表单/多步骤过程中转到哪个页面,并且由于这几乎取决于整个应用程序状态,因此我不能在我的任何一个子 reducer 中处理它。现在,我已将商店拉入 Action 创建器。我使用商店的当前状态来计算触发我的“页面”reducer 的操作对象,这会更改事件页面。我可能会在这个 Action 创建者中安装 redux-thunk 并使用 getState(),但我还没有 promise 采用这种方法。

我想这不是一个太糟糕的解决方案,因为只有一个 Action (到目前为止)必须以这种方式处理。我只是想知道是否有更好的解决方案,或者是否有办法重新构建我的状态和 reducer 以使其更容易,或者我所做的是否符合 Redux 的最佳实践。如果那里有任何类似的例子,那也会有帮助。

为了提供更多上下文,我的状态树目前如下所示:
{
order: order.result,
items: order.entities.items,
activePage: {
id: 'fulfillment'
// page info
},
pagesById: { // all the possible pages
fulfillment: {
id: 'fulfillment'
// page info
}
}
}

事件页面是用户必须在其中输入数据才能进入下一页的页面/部分。确定事件页面几乎总是取决于项目状态,有时取决于订单状态。最终结果是一个应用程序,用户连续填写一些表格,一旦表格有效就点击继续。在继续时,应用程序确定所需的下一个页面并显示它,依此类推。

编辑:我们已经尝试了结合子 reducer 实现“全局” reducer 的方法。

实现是这样的......
const global = (currentState = initialState, action) => {
switch (action.type) {
default:
return currentState
}
}


const subReducers = combineReducers({
order,
meta
})

export default function (currentState = initialState, action) {
var nextState = global(currentState, action)
return subReducers(nextState, action)
}

全局 reducer 首先在整个应用程序状态上运行,然后将其结果提供给子 reducer 。我喜欢这样一个事实,即我不再为了阅读状态的不同部分而在 Action 创建者中放置一堆逻辑。

我相信这符合 redux 的原则,因为每个 action 仍然会命中每个 reducer,并且调用 reducer 的顺序总是相同的。对这个实现有什么想法吗?

编辑:我们现在使用路由器库来处理页面状态,所以 activePage 和 pagesById 消失了。

最佳答案

如果 state.activePage 依赖于 state.order 和 state.items,您可以订阅商店,如果对“order”或“items”进行修改,则调度“checkPage” Action ,如果需要,可以设置另一个事件页面。一种方法应该连接“顶级组件”订单和项目,监听它们的值并更改事件页面/重定向

不容易理解你的顾虑,希望我的留言对你有所帮助。祝你好运

关于redux - 如何处理 redux reducer 和 action 中的横切关注点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36436941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com