React-router4路由监听的实现
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⼀切皆组件的特性和⽣命周期函数来监听路由变动
react router路由传参以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。