首页 > 解决方案 > 如果我选择其他 React Router 会改变状态?

问题描述

我正在尝试在 {title} 位置显示来自反应路由器的道具值,但我不知道是否可能。

如果路由器'/dashboard'{title}='仪表板',否则如果路由器'/payment'{title}='付款'

class Header extends React.Component {
  state = {
    title: '',
  };

  render() {
    const { title } = this.state;

  return (
     <Typography>
         {title}
     </Typography>

  <Switch>
    <Route title="Dashboard" exact path="/dashboard" component={DashboardPage} />
    <Route title="Payment" path="/payment" component={PaymentPage} />
  </Switch>
  )

标签: javascriptreactjsreact-router

解决方案


方法 1:您可以使用 withRouter 包装您的 Header 组件,该组件提供位置作为道具,其中包含路径名。您可以使用它来更改标题。

方法 2:您将一个函数作为 prop 传递给 DashboardPage,它将在 Header 组件中设置标题状态。

在 Header 组件中:

_setTitle = (title) => this.setState({ title })

传递 _setTitle 如下

<Route
  path='/dashboard'
  exact
  render={(props) => <DashboardPage {...props} setTitle={this._setTitle} />}
/>

在 DashboardPage 组件的构造函数中执行 setTitle 以设置正确的标题,如下所示:

class DashboardPage extends Component {
    constructor(props) {
      super(props);
      this.props.setTitle('Dashboard');
    }
}

对 PaymentPage 执行相同的操作。

这应该有效。让我知道这是否可以解决您的问题。


推荐阅读