【问题标题】:Update property of React component in a separate component在单独的组件中更新 React 组件的属性
【发布时间】:2016-11-30 03:18:57
【问题描述】:

我有一个带有属性 title 的 React MaterialUI AppBarcomponent,我正在根据 window.location.pathname 返回的值进行更改。因此,随着页面/网址的变化,标题也会随之变化。如下所示:

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

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

我遇到的问题是renderTitle() 不会在其他组件(所以不是AppBar)导致页面/网址更改时被执行。

例如页面上另一个单独的 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() 已经运行

感谢任何帮助,谢谢

【问题讨论】:

    标签: reactjs react-router material-ui


    【解决方案1】:

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

    react-document-title 提供了一种在单页应用程序中指定 document.title 的声明方式。 该组件也可以在服务器端使用。

    【讨论】:

      【解决方案2】:

      如果渲染 AppBar 的组件是实际路由,则可以从 react 路由器注入的 props 中读取路径名。

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

      例如在应用程序、关于、收件箱和消息中,您可以访问路由器道具。你也可以把道具传给他们的孩子。

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

      在您的函数中,只需使用参数即可返回正确的结果。现在,因为您使用的是道具,所以您的组件会在它们更改时自动更新。

      【讨论】:

        猜你喜欢
        • 2019-07-03
        • 2023-01-03
        • 2016-05-02
        • 1970-01-01
        • 1970-01-01
        • 2020-01-04
        • 1970-01-01
        • 2021-06-05
        • 2017-05-03
        相关资源
        最近更新 更多