javascript - 为什么要使用 Action Creator 回调函数而不是使用简单的对象?

标签 javascript object redux callback

我目前正在 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/

相关文章:

javascript - 如何在组件中监听 redux Action 流

ajax - 如何在redux中发出AJAX请求

javascript - 通过 JavaScript 或 jQuery 删除内部带有不间断空格的 P 标签

javascript - Raphael js 拖入 javascript 对象

javascript - 如何在没有浏览器和 yslow/firebug 等工具的情况下使用 javascript 和 cookie 测量页面速度

c++ - 对象模型的实现布局

c# - 使用 JsonConvert 将 C# 中的 JSON 转换为对象

javascript - 如何使用 JavaScript 编写 reducer 来操作此 JSON

javascript - 光滑网格中的自定义单元格编辑器未关闭

javascript - 当我将图像上传到服务器nodejs时找不到文件(使用multer)