【问题标题】:setInterval within React components and hot reloading (Webpack)React 组件中的 setInterval 和热重载(Webpack)
【发布时间】:2023-03-19 22:05:01
【问题描述】:

我想在 React 组件中重复调用一个函数,从它挂载到卸载,并使其与 webpack HMR(热重载)一起使用。

最简单的方法是按照 ReactJS 文档中的建议在 componentDidMount 中设置间隔:[1]:https://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount

componentDidMount () {
  const number = Math.floor(Math.random() * 1000) + 1
  setInterval(() => console.log('Component ' + number.toString()), 5000)
}

我已经搜索过,但找不到在 webpack HMR 为我们更新的组件调用 componentDidMount 之前清除间隔的解决方案。这意味着每次模块热重载时我们都有一个新的间隔。

注意:componentWillUnmount 在 Webpack 重新打包之前不会被调用

更新:当 HMR 设置正确时,重新捆绑应该调用 componentWillUnmount

使用 webpack HMR 实现重复延迟函数调用的最佳方法是什么?

【问题讨论】:

  • componentWillUnmount
  • 问题是componentWillUnmount在webpack重新打包之前没有被调用。

标签: reactjs settimeout setinterval webpack-hmr


【解决方案1】:

抱歉,我刚刚发现问题出在我的 webpack HMR 实现上,它没有明确卸载热路由。

如果您碰巧遇到同样的问题,您可能需要检查此提交,请查看 src/main.js 差异文件: https://github.com/davezuko/react-redux-starter-kit/commit/a602625b20ade172c829b583882ae44c150e738c

【讨论】:

    猜你喜欢
    • 2019-05-29
    • 2015-11-17
    • 2017-12-30
    • 1970-01-01
    • 2020-01-11
    • 2019-01-20
    • 1970-01-01
    • 2020-12-18
    • 2017-07-07
    相关资源
    最近更新 更多