【问题标题】:Webpack HotModule reloading with React Router render vs component使用 React Router 重新加载 Webpack HotModule 渲染与组件
【发布时间】:2019-08-14 15:56:33
【问题描述】:

我第一次使用 ReactRouter 时遇到了 HotModuleReloading 的问题。浏览器控制台将显示正确的更改更新,但窗口本身不会更新。

来自official docs

当你使用组件(而不是渲染或子组件,如下)时,路由器使用 React.createElement 从给定组件创建一个新的 React 元素。这意味着如果您为组件属性提供内联函数,您将在每次渲染时创建一个新组件。 这会导致现有组件卸载和新组件安装,而不是仅更新现有组件。当使用内联函数进行内联渲染时,请使用 render 或 children 道具(如下)。

我读到render 减少了不必要的重新渲染,这里是their docs

这允许方便的内联渲染和包装,而无需上面解释的不希望的重新安装。您可以传入一个在位置匹配时调用的函数,而不是使用组件属性为您创建一个新的 React 元素。 render prop 接收与组件 render prop 相同的所有路由 prop。

我一直在使用render 方法,如下所示:

const App = () => {
  return (
    <Switch>
      <Route exact path="/" render={() => <Home />} />
    </Switch>
  );
};

我尝试删除我的 Redux &lt;Provider&gt; 内容,但没有任何更改。所以我把渲染换成这样的组件,它工作正常:

const App = () => {
  return (
    <Switch>
      <Route exact path="/" component={Home} />
    </Switch>
  );
};

那么,这是为什么呢?我错过了什么?

【问题讨论】:

    标签: reactjs react-router react-router-v4 webpack-hmr


    【解决方案1】:

    当您使用component 时,Route 组件会将某些 props 传递给渲染组件 - 例如 locationhistorymatch 等。

    当你使用render 时,你会像&lt;Home /&gt; 一样在JSX 中渲染组件。这没有任何道具传递给它。

    如果出于某种原因,您需要使用render 而不是component,您应该传递与component 相同的道具:

    const App = () => {
      return (
        <Switch>
          <Route exact path="/" render={(props) => <Home ...props />} />
        </Switch>
      );
    };
    

    这将确保Home 获得处理路由器所需的道具。

    希望这可以帮助您深入了解它!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-23
      • 2017-05-17
      • 1970-01-01
      • 2018-01-07
      • 1970-01-01
      • 2018-01-25
      • 2018-10-28
      • 2023-03-08
      相关资源
      最近更新 更多