如何在React Router中更新路由而无需在单页面应用程序中重新安装组件?

时间:2016-06-01 20:46:34

标签: reactjs react-router redux react-router-redux reactcsstransitiongroup

我正在寻找一种美容方式"更新React / Redux / React-Router / React-Router-Redux应用程序地址栏中的路由,不带实际上导致组件在路由更改时重新安装。

我使用React CSS Transition Groups为进入路线设置动画。所以当用户来自

/home/

/home/profile/bob

动画开火。

但是,一旦开启/home/profile/bob,用户就可以向左/向右滑动以转到其他个人资料 - /home/profile/joe等。

我希望地址栏中的URL在发生这种情况时更新,但是目前导致profile组件重新挂载,重新触发CSS Transition Group,导致动画触发 - I只希望在从非配置文件路由到配置文件路由时触发该动画,而不是在配置文件路由之间切换时触发。

我希望这是有道理的。我基本上都在寻找一种美容方式"更新应用程序URL,而不强制重新安装管理该路由的组件。

2 个答案:

答案 0 :(得分:1)

如果您使用的是反应路由器,则在更改网址时会挂载/卸载。这是正常的行为。在页面之间转换是一回事,你只能在不知道你来自哪个url路径的情况下声明和进/出过渡:(

答案 1 :(得分:0)

我试图实现你所说的话。在“孩子路线”之间移动时,我可以阻止整页过渡。但我还没有能够触发子路线的特定转换(由于父路线重新渲染)。这是我提出的https://codesandbox.io/s/Dkwyg654k

import React, { Component } from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
import { CSSTransitionGroup } from 'react-transition-group';

import About  from './components/About';
import Home   from './components/Home';
import Topics from './components/Topics';

import './styles.css';

var currentRoute = ''

const getParentPathname = pathname => 
  pathname === '/'
    ? ''
    : (/([a-zA-Z])([^/]*)/).exec(pathname)[0]

class BasicExample extends Component {
  render = () =>
    <Router>
      <Route
        render={({ location, history, match }) => {

          const nextRoute = getParentPathname(location.pathname)
          const isParentRouteChange = 
                !currentRoute.includes(nextRoute) || 
                !nextRoute.includes(currentRoute)
          currentRoute = nextRoute

          return(
            <div>
              <ul>
                <li>
                  <Link to="/">Home</Link>
                </li>
                <li>
                  <Link to="/about">About</Link>
                </li>
                <li>
                  <Link to="/topics">Topics</Link>
                </li>
              </ul>

              <hr />
              <CSSTransitionGroup
//                 transitionEnter={isParentRouteChange}
//                 transitionLeave={isParentRouteChange}
                transitionEnterTimeout={500}
                transitionLeaveTimeout={500}
                transitionName={isParentRouteChange ? "fade" : "slide"}
              >
                <Switch key={location.key} location={location}>
                  <Route exact path="/"       component={Home}   location={location} key={location.key}/>
                  <Route       path="/about"  component={About}  location={location} key={location.key}/>
                  <Route       path="/topics" component={Topics} location={location} key={location.key}/>
                </Switch>
              </CSSTransitionGroup>
            </div> 
          )

        }
      }/>
    </Router>

}

render(<BasicExample />, document.body)