模块热替换
本页内容

模块热替换



模块热替换(Hot Module Replacement)是一种更新应用程序中模块而无需重新加载页面的技术。它提供了出色的开发体验,当使用 Vite 时,React Router 支持该功能。

HMR(模块热替换)会尽力在更新之间保持浏览器状态。例如,假设你在一个模态框中有一个表单,并且已经填写了所有字段。一旦你保存任何代码更改,传统的实时重载会硬性刷新页面,导致所有这些字段被重置。每次你进行更改,都必须再次打开模态框并再次填写表单。

但有了 HMR,所有这些状态在更新之间都会被保留。

React Fast Refresh

React 已经有了响应用户交互(如点击按钮)来更新 DOM 的机制,这得益于它的虚拟 DOM。如果 React 也能处理响应代码更改来更新 DOM,那岂不是太棒了?

这正是 React Fast Refresh 的目的!当然,React 专注于组件,而不是通用的 JavaScript 代码,因此 React Fast Refresh 仅处理导出的 React 组件的热更新。

但 React Fast Refresh 也有一些你应该了解的限制。

类组件状态

React Fast Refresh 不会保留类组件的状态。这包括内部返回类的高阶组件。

export class ComponentA extends Component {} // ❌

export const ComponentB = HOC(ComponentC); // ❌ Won't work if HOC returns a class component

export function ComponentD() {} // ✅
export const ComponentE = () => {}; // ✅
export default function ComponentF() {} // ✅

命名函数组件

函数组件必须是命名的,而不是匿名的,以便 React Fast Refresh 跟踪更改。

export default () => {}; // ❌
export default function () {} // ❌

const ComponentA = () => {};
export default ComponentA; // ✅

export default function ComponentB() {} // ✅

支持的导出

React Fast Refresh 只能处理组件导出。虽然 React Router 会为你管理路由导出,如 actionheaderslinksloadermeta,但任何用户定义的导出都会导致完全重新加载。

// These exports are handled by the React Router Vite plugin
// to be HMR-compatible
export const meta = { title: "Home" }; // ✅
export const links = [
  { rel: "stylesheet", href: "style.css" },
]; // ✅

// These exports are removed by the React Router Vite plugin
// so they never affect HMR
export const headers = { "Cache-Control": "max-age=3600" }; // ✅
export const loader = async () => {}; // ✅
export const action = async () => {}; // ✅

// This is not a route module export, nor a component export,
// so it will cause a full reload for this route
export const myValue = "some value"; // ❌

export default function Route() {} // ✅

👆 路由本来就不应该导出像那样的随机值。如果你想在不同路由之间重用值,请将它们放在它们自己的非路由模块中。

export const myValue = "some value";

更改 Hooks

当组件中添加或删除 Hooks 时,React Fast Refresh 无法跟踪其更改,这会导致下一次渲染时进行完全重新加载。在 Hooks 更新后,更改应再次触发热更新。例如,如果你向组件中添加一个 useState,你可能会在下一次渲染时丢失该组件的本地状态。

此外,如果你正在解构一个 Hook 的返回值,当解构的键被移除或重命名时,React Fast Refresh 将无法保留组件的状态。例如

export default function Component({ loaderData }) {
  const { pet } = useMyCustomHook();
  return (
    <div>
      <input />
      <p>My dog's name is {pet.name}!</p>
    </div>
  );
}

如果你将键 pet 改为 dog

 export default function Component() {
-  const { pet } = useMyCustomHook();
+  const { dog } = useMyCustomHook();
   return (
     <div>
       <input />
-      <p>My dog's name is {pet.name}!</p>
+      <p>My dog's name is {dog.name}!</p>
     </div>
   );
 }

那么 React Fast Refresh 将无法保留 <input /> 的状态 ❌。

组件的 Keys

在某些情况下,React 无法区分现有组件的更改和新组件的添加。React 需要 key 来消除这些情况的歧义,并在兄弟元素被修改时跟踪更改。

文档和示例 CC 4.0
编辑