react-router(v3)切换页面时不刷新页面,实现显示和隐藏子路由组件

本文介绍了如何在React-Router v3中切换子路由时保持页面状态,通过判断当前路由来控制子组件的显示与隐藏,避免页面刷新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>;
    });
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值