首页 > 解决方案 > 在 react 组件之外声明一个 const 以在不同的地方使用它

问题描述

我必须在不同的地方使用 ABC,我曾经在这两个地方有相同的定义,但是我将它提取到组件之外。

这是一种反应方式还是有更好的方法?

 const ABC = {
    jane: 0,
    john: 1
  };

 class ProjectPage extends React.Component {
    constructor(props) {
      super(props);
      resetIdCounter();
    }

   static async getInitialProps({ query }) {
      return { query, variable:ABC[query.name] };
   }

  render() {
    //code that use ABC
  }
}

标签: javascriptreactjs

解决方案


在您的项目中添加一个并行文件,例如myConfig.js. 在这个文件中,像这样导出这个常量

export const ABC = {
    jane: 0,
    john: 1,
 };

然后将这个新创建myConfig.js的导入上述反应文件(ProjectPage)中,例如:

import * as myConfig from './myConfig';
// or import only what you need directly
import { ABC } from './myConfig';

现在,只需在此文件中使用您想要的任何位置,例如myConfig.ABC;


推荐阅读