javascript - 如果我选择其他 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>
)
解决方案
方法 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 执行相同的操作。
这应该有效。让我知道这是否可以解决您的问题。
推荐阅读
- java - java类如何根据需要发送其参数?
- sql - 如何在一个表中有两个外键?(SQL-Server)
- excel - 使用 ActiveObject 在 Word (JScript, Javascript) 中选择收件人
- javascript - 显示 auth 表中的所有用户
- javascript - 同一列中具有 2 个页脚的垫表
- react-native - React 测试渲染器 JSON 没有子级的 Typescript 错误
- oracle - Oracle Forms 10.1.2 在 EDGE/CHROME 中运行
- git - 无法执行 git commit
- google-cloud-platform - 想要获取当前组织中多个项目的 Cloud SQL 实例列表
- python - 制作对象时出现“Object() 不带参数”错误