我开始使用 redux 并认为使用长 if
或 switch
语句创建 reducer 函数似乎没有组织且丑陋。因此,当状态突变逻辑存在于 Action 创建者中时,我创建了一个概念证明,但我不确定这样做是否违反了某些 Flux 或 redux 原则。我想知道将此逻辑放入分派(dispatch)的操作对象中是否有任何重大缺点。
概念验证示例
使用reducer创建存储,从分派(dispatch)的操作中执行突变方法:
import { createStore } from "redux";
const store = createStore((state, action) => {
if (action.mutation) {
const mutatedStated = action.mutation({ ...state });
return { ...state, ...mutatedStated };
}
return state;
});
然后使用方法创建 Action 创建者来生成新的状态对象:
export const updateName = (name) => {
return {
mutation(state) {
return { ...state, name };
},
type: "UPDATE_NAME",
}
}
用法:
store.dispatch(updateName("Your friend Ken"))
const createStore = Redux.createStore;
const store = createStore((state, action) => {
if (action.mutation) {
const mutatedStated = action.mutation({ ...state
});
return { ...state,
...mutatedStated
};
}
return state;
});
// inital state
store.dispatch({
type: "testing",
mutation: () => {
return {
name: "test"
}
}
});
console.log(store.getState());
// action creator
const setName = (name) => {
return {
mutation: (state) => {
return { ...state,
name
}
},
type: "set name"
}
}
store.dispatch(setName("Your friend Ken!"));
console.log(store.getState());
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.js"></script>
最佳答案
状态更新逻辑应该独立于操作,以便不同的 reducer 可以在给定相同操作的情况下以不同的方式更新状态。在操作中包含状态更新逻辑将两者结合起来,如果需要多个 reducer 来处理该操作,则必须在操作中为每个不同的 reducer 编写状态更新回调。
如果你想让你的reducer保持干净,只需将复杂的东西分解到实用函数中即可。
关于javascript - Redux 调度一个包含要从 reducer 调用的方法的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53163243/