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

标签 reactjs

在 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/

相关文章:

javascript - React函数和 "this"

javascript - 如何在使用 AnimatePresence 包装的 Next.js 页面中导航并滚动到具有 ID 的元素

javascript - 如何在阴影根中获取元素?

reactjs - 使用 Next.js 在构建时运行脚本

javascript - 使用 jquery 选择器渲染 reactjs

reactjs - Ant Design 表行类名多个条件

javascript - 如何防止授权用户将我的网站嵌入到移动应用程序中

reactjs - React this.props 未定义

reactjs - React/Relay 服务器端渲染和 SEO 友好的应用程序

javascript - React Router - 在 iF​​rame 中渲染时隐藏页眉和页脚