最近遇到了就是離開當前頁面后,返回該頁面時,需要保留離開前的狀態,對於這種情況,首先是有幾種思路
- 將該頁面的狀態全部存入到
sessionSotrage
中,等到回來時,再從頁面中去取。 - 將頁面的數據全部存入到
redux
中,再通過mapStateToProps
,通過connect
的方式引入該頁面。 - 想辦法實現一種類似
vue
的keep-alive
的功能。 - 重寫Route組件,在其內部實現該邏輯
這里由於前面兩種方法實現起來都比較容易,就不多講,主要看看第三種思路可以如何去實現
- 首先,我這種實現思路是基於
react-router
帶路由的項目。 - 由於
switch
會導致沒有匹配的路由不會被渲染,所以需要將keep-alive
的路由放到switch
外面。 - 然后我們可以看到
Route
的組件內部是可以只傳一個children
的方法的。......Route的render方法中的部分代碼,我們可以看到不管`match`有沒有匹配到,當`children`為一個方法的時候,都會去執行`children`方法。 if (component) return match ? React.createElement(component, props) : null; if (render) return match ? render(props) : null; if (typeof children === "function") return children(props); if (children && !isEmptyChildren(children)) return React.Children.only(children); return null;
- 所以我們在使用Route時,可以分兩種情況來使用
// 當不需要進行緩存的時候 <Route path={path} component={component} /> // 當需要進行緩存的時候 <Route path={path} children={props => this.renderChildren(props)} /> renderChildren = (props) => { const { match } = props; return ( <div style={ match ? { } : { position: 'absolute', zIndex: -10 } }> // 如果匹配到了就直接渲染出來,如果沒有匹配到,就直接隱藏掉該組件,但是此時組件是不會銷毀的,這樣就能保證在返回后頁面狀態的保留 <Component /> // 這個就是該路由下對應的組件 </div> ) }