我目前正在 codecademy 上学习 Redux,遇到了一些感觉多余的东西。
本类(class)给出了以下关于调用调度的过度方式的示例:
store.dispatch({type:'toggle'});
store.dispatch({type:'toggle'});
store.dispatch({type:'toggle'});
In most Redux applications, action creators are used to reduce this repetition and to provide consistency. An action creator is simply a function that returns an action object with a type property. They are typically called and passed directly to the store.dispatch() method resulting in fewer errors and an easier-to-read dispatch statement.
The above code could be rewritten using an action creator called toggle() like so:
const toggle = () => {
return { type: "toggle" };
}
store.dispatch(toggle()); // Toggles the light to 'off'
store.dispatch(toggle()); // Toggles the light back to 'on'
store.dispatch(toggle()); // Toggles the light back to 'off'
我的问题是,为什么不通过像这样创建一个对象来简化这个返回对象的 Action Creator 回调函数?
const toggle = { type: toggle }
store.dispatch(toggle);
store.dispatch(toggle);
store.dispatch(toggle);
最佳答案
const toggle = Object.freeze({ type: "toggle"})
确实工作得很好,并且适合这个特定的操作。然而,通常一个 Action 确实携带有效负载,并且要创建具有不同有效负载值的 Action ,将使用函数,例如
function openSection(index) {
return {type: "open", index};
}
你会这样称呼
store.dispatch(openSection(1))
// or
e => store.dispatch(openSection(+e.target.dataset.index))
此外,这还可以让您稍后add side effects to the action creator无需重构使用该操作的代码。
关于javascript - 为什么要使用 Action Creator 回调函数而不是使用简单的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74348931/