【问题标题】:componentDidMount fires twice when using TransitionGroup for animation使用 TransitionGroup 进行动画时,componentDidMount 会触发两次
【发布时间】:2020-05-14 07:56:26
【问题描述】:
我目前正在将react-transition-group 与react-router-dom 结合使用来为路线更改设置动画,并且效果很好。
我遇到的唯一问题是,当切换路由并且我需要在 componentDidMount 生命周期挂钩中发送或获取一些数据时,它会触发两次。我很确定这是由于react-transition-group,但我想知道是否有明显的解决方案来解决这个问题。
我发现这是因为它两次在数据库中插入一个实体,这与预期的行为相去甚远。
登录componentDidMount的转换示例
【问题讨论】:
标签:
reactjs
react-router
react-transition-group
【解决方案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>