v4版本应该也差不多的解决方法
思路很简单:就是在{this.props.children}渲染的地方进行处理,根据当前路由名称判断组件显示与隐藏。
children即this.props.children;
将children保存到全局windows中
save = (children) => {
this.routeName = children.props.route.name;
if (!window.routeCache) window.routeCache = {};
if (!window.routeCache[this.path]) window.routeCache[this.path] = {};
if (!window.routeCache[this.path][this.routeName]) {
window.routeCache[this.path][this.routeName] = children;
}
}
然后在{this.props.children}的位置使用下面的方法,判断当前路由选择对应组件进行显示和隐藏
render = () => {
return Object.keys(window.routeCache[this.path]).map((key) => {
if (key === this.routeName) return <div key={key} style={{height: '100%'}}>{window.routeCache[this.path][key]}</div>;
return <div key={key} style={{display: 'none'}}>{window.routeCache[this.path][key]}</div>;
});
}