React Router - 改变其他组件的状态

React Router - Change state of other components

使用React Router时,如何在页面路由时改变另一个组件的状态?

例如,我有一个结构如下的应用程序:

Header
==Link1 Link2==
Footer: "You are now at Home", button1, button2

当用户被路由到 Link1 时,我想更新页脚的状态,以便它知道它当前在 link1 上。例如,页脚是一个工具栏,某些按钮在 Link1 上将被禁用,但所有按钮在 Link2 和 Home 上都可用。像这样:

==Header==
==Link1 Link2==
==Content of Link1==
Footer: "You are now at Link1", button2

我能想到的解决方案是将链接的页脚和内容包装到一个大的单个组件中,并设置到整个组件的路由。但我不确定这是否是一个好习惯,因为我猜这有点违背了 "footer".

的目的

另一个想法是,也许我可以在路由运行时更改页脚组件的状态,这样页脚将在必要时重新呈现。 <Footer /> 组件因此位于主要内容之外,与 <Header /> 处于同一级别。但是,我不知道该怎么做。

有没有更好的方法来实现这个?

这是CodeSandbox上的代码片段,希望它能更好地说明我的问题。

CodeSandbox demo

一种方法是在 Footer 上使用 withRouter HOC,以便在更改路线时接收道具。

代码更改

import { BrowserRouter, Route, Link, withRouter } from "react-router-dom";

然后

<BrowserRouter>
  <div>
    <Route path="/" exact component={Home} />
    <Route path="/section1" component={SectionOne} />
    <WrappedFooter />
  </div>
</BrowserRouter>

然后

const WrappedFooter = withRouter(Footer);

您现在可以使用页脚中的 this.props.location.pathname 从路由器访问当前匹配的路由。您应该在开关中使用实际路径 让文字, {位置} = this.props

switch (location.pathname) {
  case '/': {
    text = 'Home'
    break
  }
  case '/section1': {
    text = 'Section One'
    break
  }
}

https://codesandbox.io/s/8y051k9qoj