gpt4 book ai didi

reactjs - componentWillMount 内的 'require' 是否是反模式?

转载 作者:行者123 更新时间:2023-12-03 13:34:40 25 4
gpt4 key购买 nike

在 componentWillMount 中“require”是反模式吗?我正在尝试根据当前用户区域动态加载区域设置。

componentWillMount(){
if (localStorage.getItem('locale') === 'da') {
require('moment/locale/da')
moment.locale('da')
}
}

谢谢!

最佳答案

根据您使用的捆绑代码的工具,结果可能会有所不同。如果您使用 Webpack,它将就地解析“require”和“import”,而不是跳过类方法或任何内容。这意味着你不会真正从中受益。 bundle 的大小不会是最佳的,但可能会增加射中脚的机会。

但是,在 Webpack 3 中,Webpack 中有一个名为延迟加载的功能,允许您在运行时请求模块。 Webpack 将负责将所有必要的 JS 代码放在用户浏览器的运行时上,以从服务器请求模块并执行它(想象一下创建一个“脚本”元素并将其附加到 document 中)。

a note on lazy loading in official Webpack documentation这表明不同库之间实现此功能的潜在差异。这样,代码将如下所示

async componentDidMount() { // <- note that componentWillMount isn't the best place to lazy-load a remote module, see @TryingToImprove's comment
const da = await import('moment/locale/da'); // <- Webpack will add its magic here
moment.locale(da);
}

此外,请阅读有关 dynamic imports 的更多信息.

那么,回答你的问题

Is it anti-pattern to 'require' inside componentWillMount?

恐怕现在仍是 2018 年初,至少以您所描述的方式,除非特别小心。

ESLint 实际上有一个规则,global-require ,当“import”或“require”语句出现在全局范围之外的任何地方时,它会自动挥舞一个标志。

关于reactjs - componentWillMount 内的 'require' 是否是反模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48623367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com