最近在寫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>
複製代碼
<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>
複製代碼