React-router 4路由监听

React-router 4

React Router4是一个纯React重写的包,如今的版本中已不须要路由配置,一切皆组件。react

问题出发点

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

思路

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

项目目录结构

10.png

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>
        )
    }
}
复制代码

在这个组件中,当路由变更,咱们都能实时监听,获取路由来改变titleapp

总结

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

相关文章
相关标签/搜索