首页 > 解决方案 > React Router 重定向时的动画过渡

问题描述

我正在探索路线动画和基本示例完美地工作。但是如果在动画 Route 组件中使用重定向,它会因不定式渲染循环而崩溃。

演示:https ://codesandbox.io/embed/v3j736jvwl

转载:按重定向链接

如果我删除 Switch 组件上的位置道具,它可以在没有动画的情况下工作:

  <Switch>
    <Route exact path="/redirect" component={RedirectToMain} />
    <Route exact path="/hsl/:h/:s/:l" component={HSL} />
    <Route exact path="/rgb/:r/:g/:b" component={RGB} />
    <Route render={() => <div>Not Found</div>} />
  </Switch>

我希望页面重定向的动画不会崩溃。

标签: javascriptreactjsreact-router

解决方案


您不能使用重定向链接在重定向组件内重定向。而是使用这样的东西:

https://codesandbox.io/embed/v3j736jvwl

class RedirectToMain extends React.Component {
  componentDidMount() {
    this.props.history.push('/');
  }

  render () {
    return (
      <div
        style={{
          ...styles.fill,
          ...styles.hsl,
          background: `red`
        }}
      >
      </div>
    );
  }

}

推荐阅读