react-router4 跳轉路由如何隱藏組件而不是卸載。

最近在寫react項目的時候遇到這麼一個場景,主頁面訪問頻繁,可是有些頁面返回的時候須要保持跳出時候的狀態,有些頁面要從新load組件。一開始遇到這個問題的時候,以爲是否是隻能把須要保持當前狀態的跳轉頁面寫成一個組件,而不去跳轉路由,可是這樣的頁面是在是有點多,這樣會使主頁面變得很龐大,因此只能想辦法如何跳出路由時候不卸載。當時以爲很困難,直到看到了children這個屬性以後才發現這個事情真的很簡單。。。react

children,react-router-dom中route組件的一個屬性,不少人可能沒有發現過這個屬性,這個屬性其實容易理解,就是無論路由匹配不匹配都會渲染在頁面中,來看一下這個例子;編程

render() {
    return (
        <Router>
            <Route path={'/my'} exact children={()=>{
                return <div>my page</div>}
            }>
            </Route>
            <Route path={'/home'} exact component={HomePage}/>
            <Route path={'/person'} exact component={PersonPage}/>
        </Router>
    );
  }
}

class HomePage extends Component {
    render() {
        return (
            <div>
              Home Page
            </div>
        );
    }
}
const PersonPage = ()=>{
    return (
        <div>
            Person Page
        </div>
    );
}
複製代碼

來,咱們看一下效果。 bash

這就是children的效果,明明匹配的路由是person,可是卻出現了'/my'的內容。不過這就是正是這個需求想要的,熟悉react編程的同窗都知道,react都是函數,能夠說是把函數式編程發揮到了極致,因此這個函數裏面確定有參數,因此咱們打印一下這個children裏面的參數,react-router

<Route path={'/my'} exact children={(props)=>
    console.log(props);
    return <div>my page</div>}
 }></Route>
複製代碼

看見了參數,是否是一下就明白瞭如何實現效果了把, 因此咱們只要判斷一下是不是咱們須要保持狀態的路由,是的話就把children的節點隱藏點,不是的話就刪除掉就能實現啦。

<Route path={'/my'} exact children={(props)=>{
    console.log(props);
    return props.location.pathname !== '/person'
        ?
        <div style={{display: props.location.pathname !== '/my' ? 'none': 'block'}}>my page</div>
        :
        ''
}}></Route>
複製代碼

這樣就能實現咱們的須要了。不過這個屬性不能用在switch裏面,聽說這是因爲react的分型機制決定的,因爲能力較差,還不能解釋爲何不能再switch裏面使用,因此還請大佬們請教。。。
相關文章
相關標籤/搜索