What is the purpose of constants in redux?

综合技术 2017-11-15

For example from this example:

export const ADD_TODO = 'ADD_TODO'
export const DELETE_TODO = 'DELETE_TODO'
export const EDIT_TODO = 'EDIT_TODO'
export const COMPLETE_TODO = 'COMPLETE_TODO'
export const COMPLETE_ALL = 'COMPLETE_ALL'
export const CLEAR_COMPLETED = 'CLEAR_COMPLETED'

It's not like you're saving characters. The variable name is exactly the same as the string, and will never change. I understand making constants if one day you were doing to do something like:

ADD_TODO = 'CREATE_TODO'

but that never happens. So what purpose do these constants serve?

You are right, it is not about saving characters however after code minification you can save some space.

In redux you use those constants at least in two places - in your reducers and during actions creation. So it's much convenient to define a constant once in some file e.g. actionTypes.js

export const ADD_TODO = 'ADD_TODO';
export const DELETE_TODO = 'DELETE_TODO';
export const EDIT_TODO = 'EDIT_TODO';
export const COMPLETE_TODO = 'COMPLETE_TODO';
export const COMPLETE_ALL = 'COMPLETE_ALL';
export const CLEAR_COMPLETED = 'CLEAR_COMPLETED';

And then require it in actions creator file e.g. actions.js

import { ADD_TODO } from './actionTypes';

export function addTodo(text) {
  return { type: ADD_TODO, text };
}

And in some reducer

import { ADD_TODO } from './actionTypes';

export default (state = [], action) => {
  switch (action.type) {
    case ADD_TODO:
      return [
        ...state,
        {
          text: action.text,
          completed: false
        }
      ];
    default:
      return state
  }
};

It allows you to easily find all usages of that constant across the project (if you use an IDE). It also prevents you from introducing silly bugs caused by typos -- in which case, you will get a ReferenceError
immediately.

您可能感兴趣的

使用React、 Redux 和 SVG 开发游戏(一) 本文翻译自: Developing Games with React, Redux, and SVG - Part 1 转载英文原作请注明原作者与出处。转载本译本请注明 译者 与 译者博客 这段太长别看:在这系列教程中,你将学会如何使用 React 和 Redux 去控制一堆...
React + Redux 性能优化(二)工具篇: Immutablejs... 建议在阅读完上一篇 React + Redux 性能优化(一):理论篇 之后再开始本文的旅程,本文的很多概念和结论,都在上篇做了详细的讲解 这会是一篇长文,我们首先会讨论使用 Immutable Data 的正当性;然后从功能上和性能上研究使用 Immutablejs 的技术的必要性 我...
Cedux: Experimenting with the Redux Model in C The world of embedded software development can feel like a very isolated place. Earlier in my career, when I was doing mostly embedded work, I remembe...
ABC of Redux Hello folks! Lately, React and Redux have been the talk of the town and I've been playing around with it for a while and learnt a few nuance...
说个react-redux生产环境在线追踪action,state流的黑魔法... 用react,react-redux开发前端的时候,在开发环境,我们会enable redux dev tool extension,方便我们在线调试问题,redux这种单向数据流,状态驱动的好处就体现的淋漓尽致了。但是如果在生产环境,通常都会disable掉这样的浏览器扩展,一旦有了问题,我们很难...