2016-07-26 108 views
0

我有一个属性为title的React MaterialUI AppBar组件,我根据window.location.pathname返回的值进行更改。所以当页面/网址改变时,标题会随着它改变。看起来像下面的东西:在一个单独的组件中更新React组件的属性

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

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

我遇到的是,renderTitle()没有得到,如果不同的组件(所以不是AppBar)导致页面/ URL变化执行的问题。

E.g.页面上的另一个单独的React组件会触发页面更改,我希望这个页面可以用renderTitle()作为触发器,但它不会...因此title属性不会更新。所以,如果我从/home导航到/login,会发生以下情况:

  1. 路径是/home
  2. 用户按下运行功能,submit(),它是用来改变页面W /反应路由器按钮
  3. renderTitle()在这点上运行,但window.location.pathname前一页
  4. submit()改变页面仍然回到/login
  5. window.location.pathname现在正确设置为/login,但为时已晚renderTitle()已经运行

任何帮助表示赞赏,感谢

回答

1

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

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

0

如果您的呈现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中,您可以访问路由器的道具。你也可以将道具传递给他们的孩子。

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

而在你的函数只是使用参数返回正确的结果。现在,因为您正在使用道具,您的组件会在更改时自动更新。

相关问题