React-router 4
React Router4是一個(gè)純React重寫(xiě)的包,現(xiàn)在的版本中已不需要路由配置,一切皆組件。
問(wèn)題出發(fā)點(diǎn)
最近在一個(gè)新的H5項(xiàng)目中使用了react router 4 ("react-router-dom": "^4.2.2"),項(xiàng)目中的一部分頁(yè)面是需要給app客戶(hù)端的同學(xué)使用,這樣H5項(xiàng)目中的title就不能一成不變,需要顯示對(duì)應(yīng)頁(yè)面的title,所以,我們就需要去監(jiān)聽(tīng)路由變動(dòng)來(lái)更改title。
思路
在react中,例如:在父路由中有兩個(gè)子路由,兩個(gè)子路由組件的內(nèi)容都屬于父路由中的一部分,通過(guò)切換子路由來(lái)顯示不同內(nèi)容,這種情況下,父組件中的生命周期函數(shù)componentWillUpdate都會(huì)在切換子路由時(shí)被觸發(fā)。按照這個(gè)思路結(jié)合react-router 4一切皆組件的特性,我們可以用一個(gè)IndexPage組件來(lái)放置所有的一級(jí)路由(其他多級(jí)路由就可以放到對(duì)應(yīng)一級(jí)路由組件中),當(dāng)我們切換路由是,就可以在這個(gè)IndexPage組件中實(shí)時(shí)監(jiān)聽(tīng)路由的變動(dòng)了。
項(xiàng)目目錄結(jié)構(gòu)
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> ... 項(xiàng)目一級(jí)路由 ... </Switch> </div> ) } }
在這個(gè)組件中,當(dāng)路由變動(dòng),我們都能實(shí)時(shí)監(jiān)聽(tīng),獲取路由來(lái)改變title
總結(jié)
利用react-router 4一切皆組件的特性和生命周期函數(shù)來(lái)監(jiān)聽(tīng)路由變動(dòng)
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com