【问题标题】:componentDidMount fires twice when using TransitionGroup for animation使用 TransitionGroup 进行动画时,componentDidMount 会触发两次
【发布时间】:2020-05-14 07:56:26
【问题描述】:

我目前正在将react-transition-groupreact-router-dom 结合使用来为路线更改设置动画,并且效果很好。

我遇到的唯一问题是,当切换路由并且我需要在 componentDidMount 生命周期挂钩中发送或获取一些数据时,它会触发两次。我很确定这是由于react-transition-group,但我想知道是否有明显的解决方案来解决这个问题。

我发现这是因为它两次在数据库中插入一个实体,这与预期的行为相去甚远。

登录componentDidMount的转换示例

【问题讨论】:

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


    【解决方案1】:

    我发现这是我的Switch 组件see this github issue 的问题

    基本上,您需要在包装好的 Switch 组件中使用 location 属性。

    【讨论】:

      【解决方案2】:

      这是来自 github 问题的 sn-p,因此您不必点击。

      将位置添加到 Switch:<Switch location={location}>

      <TransitionGroup component="main">
        <CSSTransition
          key={location.pathname}
          timeout={timeout}
          exit={false}
          classNames="fade">
          <Switch location={location}> // <- Here it is!
            <Route exact path="/" component={Home} />
            <Route path="/blog" component={BlogList} />
            <Route path="/about" component={About} />
            <Route path="/contact" component={Contact} />
            <Route component={NotFound} />
          </Switch>
        </CSSTransition>
      </TransitionGroup>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-27
        • 2018-11-06
        • 2020-09-29
        • 1970-01-01
        • 2017-01-02
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        相关资源
        最近更新 更多