我必须在不同的地方使用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
}
}
答案 0 :(得分:2)
在项目中添加一个并行文件,例如myConfig.js
。在此文件内,将const导出为
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
之类的任何位置即可