React create constants file

后端 未结 4 1195
盖世英雄少女心
盖世英雄少女心 2021-01-31 07:08

How to create constants file like: key - value in ReactJs,

ACTION_INVALID = \"This action is invalid!\"

and to use that in other components

4条回答
  •  情深已故
    2021-01-31 07:49

    One way to do that (not so different from other answers though) is to create a bare constants.js file and add your constants there.

    module.exports = Object.freeze({
      ACTION_INVALID: 'This action is invalid',
      ACTION_VALID: 'Some other action',
    });
    

    Then you can import it

    import ConstantsList from './constants';
    

    and use

    console.log(ConstantsList.ACTION_INVALID)
    

    As the name suggests, Object.freeze() freezes objects and stops anyone from changing the values. Please note: if the values are objects themselves they are changeable (unless they are also frozen)

提交回复
热议问题