javascript - 在 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
}
}
解决方案
在您的项目中添加一个并行文件,例如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
;
推荐阅读
- android - 如何在我的片段中用适配器数据填充我的回收站视图?
- c# - 角度 sin 返回锐角的负数
- php - 如何限制用户只上传纯 html 文件
- csv - 在 Odoo 13 中导入文件 excel 失败。如何?
- vue.js - Vue PWA Precache 清单与 HTML 预取链接
- android - 来自 android-beacon-library 的 ScanJob 中的 ConcurrentModificationException
- circuit-sdk - Q: Google Function 中的client.logon 过期
- macros - Julia:宏、表达式和 Meta.parse
- php - 如何模仿原生 404 页面?
- c - 非终止函数问题(无依赖关系)