【问题标题】:React HMR does not render even though an update is detected即使检测到更新,React HMR 也不会呈现
【发布时间】:2018-10-14 13:18:10
【问题描述】:

我的index.jsx 中有以下内容:

const store = configureStore();
const MOUNT_NODE = document.getElementById('root');

const render = () => {
  ReactDOM.render(
    <Provider store={store}>
      <Routes />
    </Provider>,
    MOUNT_NODE,
  );
};

if (module.hot) {
  module.hot.accept('routes.jsx', () => {
    ReactDOM.unmountComponentAtNode(MOUNT_NODE);
    render();
  });
}
render();

这会呈现初始应用。现在,当我更改任何文件时,我会在浏览器的控制台中看到以下日志。

[HMR] bundle rebuilding
[HMR] bundle rebuilt in 285ms
[HMR] Checking for updates on the server...
[HMR] Updated modules:
[HMR]  - ./src/js/components/SomeComponent/SomeComponent.jsx
[HMR]  - ./src/js/components/App.jsx
[HMR]  - ./src/js/routes.jsx
[HMR] App is up to date.

此日志表明检测到更新并且模块已更新。另外,我在“网络”选项卡中看到加载了一个新脚本,&lt;head&gt; 标记闪烁显示它加载了新脚本。我检查了脚本,它包含我的更改。

但是,我没有看到我的页面更新。整个页面快速闪烁显示render() 函数被调用但更改不存在。

我正在使用来自https://github.com/react-boilerplate/react-boilerplate 的大部分 HMR 和 webpack 设置。

我不知道去哪里寻找发生的事情。任何帮助表示赞赏。

编辑:

我刚刚发现module.hot.accept() 只被调用一次,用于第一次更新。我第二次更改文件时不会调用它。

编辑 2:

当我尝试使用 module.hot.accept(() => {}) 时,它似乎可以工作,但是减速器无法正常工作,并且出现此错误:

提供者不支持即时更改store。您很可能会看到此错误,因为您更新到 Redux 2.x 和 React Redux 2.x,它们不再自动热重载减速器。有关迁移说明,请参阅 https://github.com/reactjs/react-redux/releases/tag/v2.0.0

因此,对此我能做任何事情的唯一方法是拥有两个module.hot.accept,一个与App.jsx,另一个与reducers.jsx。仍然没有运气弄清楚到底出了什么问题。

【问题讨论】:

  • 您使用的是哪个路由器 npm?还包括您如何处理路线
  • 这有关系吗?
  • 查看我的工作 HMR 样板(master 分支安装了 react-hot-module):github.com/mattcarlotta/Webpack-React-Boilerplate
  • 我没有在我的项目中使用react-hot-loader,只是 webpack HMR 插件。不过感谢您的链接,它看起来很整洁。
  • 我实际上最终使用react-hot-loader 来解决这个问题。我找不到我当前的设置有什么问题??????,感谢提示@mattcarlotta

标签: javascript reactjs webpack webpack-hmr


【解决方案1】:

我遇到了同样的问题

对于未来的任何人,您是否尝试过这个?

//My root component (that also use redux), but can be any component one by one in case you want to specific compontents with hot reload


import {hot} from "react-hot-loader/root"
import React, { Component } from 'react';
import { BrowserRouter as Router } from 'react-router-dom'
import { Provider } from "react-redux"
import { ExtReact } from '@sencha/ext-react' 

import store from "./redux/store"
import Layout from './Layout';

// Enable responsiveConfig app-wide. You can remove this if you don't plan to build a responsive UI.

/**
 * The main application view
 */



class App extends Component {
  render() {
    return (
      <Router>
        <Provider store={store}>
          <Layout />
        </Provider>
      </Router>
    );
  }
}

export default hot(App);

【讨论】:

  • 还有一个变种,当你想通过import {hot} from "react-hot-loader export default hot(module)(**your compontent**) 一个接一个地热重载你的组件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-30
  • 2021-11-06
  • 1970-01-01
  • 2022-07-19
  • 1970-01-01
  • 2019-05-30
相关资源
最近更新 更多