使用 TransitionGroup 进行动画时,componentDidMount 会触发两次
componentDidMount fires twice when using TransitionGroup for animation
我目前正在使用 react-transition-group
in conjunction with react-router-dom
来制作路线变化的动画,效果很好。
我遇到的唯一问题是,当切换路由并且我需要在 componentDidMount
生命周期挂钩中发送或获取一些数据时,它会触发两次。我相当确定这是由于 react-transition-group
但我想知道是否有解决此问题的明显方法。
我发现这个是因为它在数据库中插入了两次实体,这与预期的行为相去甚远。
登录时的转换示例 componentDidMount
我发现这是我的 Switch
组件的问题,see this github issue
基本上,您需要在包装的 Switch
组件中使用 location
道具。
这是 github 期的摘录,因此您无需点击查看。
将位置添加到交换机:<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>
我目前正在使用 react-transition-group
in conjunction with react-router-dom
来制作路线变化的动画,效果很好。
我遇到的唯一问题是,当切换路由并且我需要在 componentDidMount
生命周期挂钩中发送或获取一些数据时,它会触发两次。我相当确定这是由于 react-transition-group
但我想知道是否有解决此问题的明显方法。
我发现这个是因为它在数据库中插入了两次实体,这与预期的行为相去甚远。
登录时的转换示例 componentDidMount
我发现这是我的 Switch
组件的问题,see this github issue
基本上,您需要在包装的 Switch
组件中使用 location
道具。
这是 github 期的摘录,因此您无需点击查看。
将位置添加到交换机:<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>