最近遇到了就是离开当前页面后,返回该页面时,需要保留离开前的状态,对于这种情况,首先是有几种思路
- 将该页面的状态全部存入到
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> ) }