【问题标题】:How to prevent component from unmounting immediately when using React Router V4使用 React Router V4 时如何防止组件立即卸载
【发布时间】:2020-07-23 22:16:06
【问题描述】:

我正在使用 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'));

对此的任何帮助将不胜感激!谢谢

【问题讨论】:

    标签: reactjs react-router react-router-v4 react-transition-group


    【解决方案1】:

    派对迟到了,你可能已经自己解决了这个问题,但为了记录在谷歌搜索这个问题的人们:检查你的 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;
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 2016-01-14
      • 1970-01-01
      • 2019-03-19
      相关资源
      最近更新 更多