【发布时间】:2019-01-12 00:03:54
【问题描述】:
我正在尝试在我的应用程序中对减速器进行更具防御性的编码,因为我的团队使用预先存在的代码作为新更改的模板。出于这个原因,我试图涵盖所有与不变性的潜在偏差。
假设您有一个如下所示的初始状态:
const initialState = {
section1: { a: 1, b: 2, c: 3 },
section2: 'Some string',
};
还有一个 reducer 处理这样的动作:
export default function(state = initialState, action) {
switch(action.type) {
case SOME_ACTION:
return { ...state, section1: action.payload.abc };
}
return state;
}
然后你可以有一个调度器来执行以下操作:
function foo(dispatch) {
const abc = { a: 0, b: 0, c: 0 };
dispatch({ type: SOME_ACTION, payload: { abc } });
// The following changes the state without dispatching a new action
// and does so by breaking the immutability of the state too.
abc.c = 5;
}
在这种情况下,虽然 reducer 通过创建旧状态的浅表副本并仅更改更改的位来遵循不变性模式,但调度程序仍然可以访问 action.payload.abc 并可以对其进行变异。
也许 redux 已经创建了整个操作的深层副本,但还没有找到任何提到这一点的来源。我想知道是否有一种方法可以简单地解决这个问题。
【问题讨论】:
-
您是否考虑过编写自己的基本中间件来处理它?
-
我曾考虑创建一个中间件,在传递操作之前对其进行深度克隆,但想看看是否有更多现成的解决方案。不过,我描述的中间件听起来效率很低。
标签: javascript redux immutability