React路由器在更改路径时重新启动子项(不进行协调)

den*_*iro 10 javascript reactjs react-router

我有一种情况,很少的路由由相同的组件组成,我想保持其状态,但有了这种行为,这是相当不可能的.

实例(查看经过的秒数):https: //csb-43lp1km647-nkiinaibit.now.sh

CodeSandbox:https://codesandbox.io/s/43lp1km647

当然,我可以在更改路线时保存和恢复计时器的状态,但我的应用程序有一个无限的CSS过渡作为背景(不是在每个路线上).

我正在尝试添加密钥,甚至门户网站,但它仍然可以重新安装所有内容.

有没有办法强制执行典型的React的对帐(仅重新安装必须重新安装的元素)?

更新:刚发现<Switch />它将呈现所有内容,直到找到匹配的元素,并且可以是某个<Route />元素或任何元素,除了它在里面<Fragment />.

码:

<Router history={history}>
  <Switch>
    <Route path="/third" component={RouteWithoutTimer} />
    <React.Fragment>
      <Timer />
      <Route exact path="/" component={FirstRoute} />
      <Route path="/second" component={SecondRoute} />
    </React.Fragment>
  </Switch>
</Router>
Run Code Online (Sandbox Code Playgroud)

编辑React路由器会在更改路径时重新启动子项

或者使用通配符路由:

<Router history={history}>
  <Switch>
    <Route path="/third" component={RouteWithoutTimer} />
    <React.Fragment>
      <Timer />
      <Switch>
        <Route exact path="/" component={FirstRoute} />
        <Route component={NotFoundRoute} />
      </Switch>
    </React.Fragment>
  </Switch>
</Router>
Run Code Online (Sandbox Code Playgroud)

这不是我想要的解决方案,但它运作正常.

riw*_*iwu 2

您正在每个路由中安装一个新实例Timer
如果你想跨路由共享一个组件,你应该将它提升到路由的父组件:

<React.Fragment>
  <Timer />
  <Switch>
    <Route exact path="/" component={FirstRoute} />
    <Route path="/second" component={SecondRoute} />
  </Switch>
</React.Fragment>
Run Code Online (Sandbox Code Playgroud)

编辑 React 路由器在更改路由时重新安装子级