在我的反应组件中,我试图根据传入的参数检索文件,例如
const Section = () => {
const params = useParams();
const sectionId = params.sectionId;
const regex = new RegExp(`Section${sectionId}.json$`);
const section = require.context('../json', false, regex);
它失败了,并出现
__webpack_require__(...).context is not a function
错误,因为根据 webpack 文档:The arguments passed to require.context must be literals!
所以我最终使用文字检索所有文件,然后根据参数获取我需要的文件,例如
const sections = require.context('../json', false, /Section[1-9].json$/);
const sectionKey = Object.keys(sections).filter(key => regex.test(key));
const section = sections[sectionKey];
我发现这样的解决方案相当不方便,并且在文件数量很大的情况下可能无法很好地扩展。
解决这个问题的正确方法是什么?
您只需替换这一行即可:
const regex = new RegExp(`Section${sectionId}.json$`);
有了这个:
const regex = RegExp(`Section${sectionId}.json$`);
我刚刚删除了
new
关键字。