在单独的组件中更新 React 组件 属性

Update property of React component in a separate component

我有一个带有 属性 title 的 React MaterialUI AppBar 组件,我正在根据 window.location.pathname 返回的值进行更改。因此,随着 page/url 的变化,标题也会随之变化。看起来像下面这样:

<AppBar
title={this.renderTitle()}
/>

renderTitle() {
if (window.location.pathname === '/home'
 return 'home';
} else if (window.location.pathname === '/login'
return 'login';
}

我 运行 关注的问题是,如果不同的组件(因此不是 AppBar)导致 page/url 更改,renderTitle() 不会执行。

例如页面上的另一个单独的 React 组件会触发页面发生变化,我希望通过触发器 renderTitle(),但它不会……因此 title 属性 永远不会更新。因此,如果我从 /home 导航到 /login,将发生以下情况:

  1. 路径名是 /home
  2. 用户按下一个按钮,该按钮具有 运行 功能 submit(),用于更改页面 react-router
  3. renderTitle()此时是运行,但是window.location.pathname还是返回上一页
  4. submit() 将页面更改为 /login
  5. window.location.pathname 现在已正确设置为 /login,但为时已晚,因为 renderTitle() 已经 运行

感谢任何帮助,谢谢

最好的方法是使用 react-document-title 库。 来自文档:

react-document-title provides a declarative way to specify document.title in a single-page app. This component can be used on server side as well.

如果您呈现 AppBar 的组件是一个实际的路由,您可以只从反应路由器注入的道具中读取路径名。

<Router>
   <Route path="/" component={App}>
     <Route path="about" component={About} />
     <Route path="inbox" component={Inbox}>
       <Route path="messages/:id" component={Message} />
     </Route>
   </Route>
 </Router>

例如,在 App、About、Inbox 和 Message 中,您可以访问路由器道具。你也可以将道具传递给他们 children.

render() {
  return (
   <AppBar
     title={this.renderTitle(this.props.location.pathname)}
   />
  );
}

并且在您的函数中只需使用参数即可 return 获得正确的结果。现在因为你正在使用 props 你的组件会在它们改变时自动更新。