首页 > 解决方案 > 使用 React Router V4 时如何防止组件立即卸载

问题描述

我正在使用 react-transition-group 的标签在使用 react-router-v4 的路由之间创建动画。我正在使用标签根据状态的变化在我的代码中的路由之间切换。我遇到的问题是,当触发 a 时,组件会立即卸载,然后再给退出动画时间播放。新路线动画正确。

我试图通过在 React Transition Group 网站上关注这个页面来解决这个问题:https ://reactcommunity.org/react-transition-group/with-react-router

它承认我在立即卸载组件时遇到的问题,但我的解决方案似乎不起作用。

const routes = [
  { path: '/', name: 'Dashboard', Component: Dashboard },
  { path: '/detailedview', name: 'DetailedView', Component: DetailedView },
  { path: '/dashboardloop', name: 'DashboardLoop', Component: DashboardLoop },
]

function Example() {
  return (
    <Router>
      <>
        <Container className="container">
          {routes.map(({ path, Component }) => (
            <Route key={path} exact path={path}>
              {({ match }) => (
                <CSSTransition
                  in={match != null}
                  timeout={500}
                  classNames="page"
                  unmountOnExit
                >
                  <div className="page">
                    <Component />
                  </div>
                </CSSTransition>
              )}
            </Route>
          ))}
        </Container>
      </>
    </Router>
  )
}

ReactDOM.render((
  <Example/>
), document.getElementById('root'));

任何帮助将不胜感激!谢谢

标签: reactjsreact-routerreact-router-v4react-transition-group

解决方案


派对迟到了,你可能已经自己解决了这个问题,但是为了记录在谷歌上搜索这个问题的人:检查你的 css。

CSSTransition 依赖于四个 css 类(如文档中所述):

/* Starting style of enter animation, i.e when element is still invisible */
.page-transition-enter{
}

/* How the element will look on the page + transition (which does the animation) goes here*/
.page-transition-enter-active{
}

/* Start of exit animation, usually how the element looks on the page */
.page-transition-exit{
}

/*The end-style of exit-animation + transition */
.page-transition-exit-active{
}

React 过渡组文档 ( http://reactcommunity.org/react-transition-group/css-transition ) 中的一个简单过渡示例:

.page-enter {
  opacity: 0;
}
.page-enter-active {
  opacity: 1;
  transition: opacity 200ms;
}
.page-exit {
  opacity: 1;
}
.page-exit-active {
  opacity: 0;
  transition: opacity 200ms;
}

由于您的元素在没有动画的情况下卸载,但在进入时动画,您似乎很可能错过了最后两个类中的某些内容。或者完全缺少一个或两个类。


推荐阅读