React-router4路由监听的实现

2018-10-15 18:05

阅读:559

React-router 4

React Router4是一个纯React重写的包,现在的版本中已不需要路由配置,一切皆组件。

问题出发点

最近在一个新的H5项目中使用了react router 4 (react-router-dom: ^4.2.2),项目中的一部分页面是需要给app客户端的同学使用,这样H5项目中的title就不能一成不变,需要显示对应页面的title,所以,我们就需要去监听路由变动来更改title。

思路

在react中,例如:在父路由中有两个子路由,两个子路由组件的内容都属于父路由中的一部分,通过切换子路由来显示不同内容,这种情况下,父组件中的生命周期函数componentWillUpdate都会在切换子路由时被触发。按照这个思路结合react-router 4一切皆组件的特性,我们可以用一个IndexPage组件来放置所有的一级路由(其他多级路由就可以放到对应一级路由组件中),当我们切换路由是,就可以在这个IndexPage组件中实时监听路由的变动了。

项目目录结构

src/app.js

... export default class App extends Component { render() { return ( <Router> <Route path=/ component={IndexPage}/> </Router> ) } }

src/pages/index.js

... export default class IndexPage extends Component { componentDidMount() { this.updateTitle(this.props); } componentWillUpdate(nextProps) { this.updateTitle(nextProps); } updateTitle = (props) => { routes.forEach(route => { if (route.path === props.location.pathname) { document.title = route.title; } }) } render() { return ( <div className=index-page> <Switch> ... 项目一级路由 ... </Switch> </div> ) } }

在这个组件中,当路由变动,我们都能实时监听,获取路由来改变title

总结

利用react-router 4一切皆组件的特性和生命周期函数来监听路由变动

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。


评论


亲,登录后才可以留言!