You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用react-router与react-transition-group实现路由动画时遇路由未匹配问题

解决React Router v6路由切换动画中的“No routes matched location”错误

问题根源

你的代码混用了React Router v5和v6的API,导致路由匹配逻辑失效:

  • Routes组件在v6中没有render属性,你沿用了v5的写法
  • Route组件的component属性在v6中已被element替代
  • v6中Route默认精确匹配,exact属性已被移除
  • AnimatedSwitch内部的路由匹配写法不符合v6规范

修正步骤

1. 重构AnimatedSwitch组件

改用v6的useLocation钩子获取路由位置,调整TransitionGroup和Routes的嵌套结构:

import React from 'react';
import { Routes, useLocation } from 'react-router-dom';
import { CSSTransition, TransitionGroup } from 'react-transition-group';

const AnimatedSwitch = ({ animationClassName, animationTimeout, children }) => {
  const location = useLocation();

  return (
    <TransitionGroup style={{ flex: 1, position: 'relative' }}>
      <CSSTransition
        key={location.key}
        timeout={animationTimeout}
        classNames={animationClassName}
      >
        <div style={{ position: 'absolute', inset: 0 }}>
          <Routes location={location}>{children}</Routes>
        </div>
      </CSSTransition>
    </TransitionGroup>
  );
};

export default AnimatedSwitch;

2. 更新AnimatedRoute组件

适配v6的Route API,使用element属性并保留绝对定位:

import React from 'react';
import { Route } from 'react-router-dom';

const AnimatedRoute = ({ element, ...props }) => (
  <Route 
    {...props} 
    element={<div style={{ position: 'absolute', inset: 0 }}>{element}</div>} 
  />
);

export default AnimatedRoute;

3. 修正主Router组件

替换component为element,移除多余的exact属性:

import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import App from '../App';
import Biographical from './Biographical';
import Noticias from './News';
import Tienda from './Shop';
import AnimatedSwitch from './Animated-Switch';
import AnimatedRoute from './Animated-Router';

const Router = () => (
  <BrowserRouter>
    <div className="Router">
      <AnimatedSwitch animationClassName="page-slide" animationTimeout={300}>
        <AnimatedRoute path="/" element={<App />} />
        <AnimatedRoute path="/biografia" element={<Biographical />} />
        <AnimatedRoute path="/noticias" element={<Noticias />} />
        <AnimatedRoute path="/tienda" element={<Tienda />} />
      </AnimatedSwitch>
    </div>
  </BrowserRouter>
);

export default Router;

4. 补充CSS动画样式

确保你的CSS中定义了page-slide相关的过渡动画,比如:

.page-slide-enter {
  transform: translateX(100%);
}
.page-slide-enter-active {
  transform: translateX(0);
  transition: transform 300ms ease-out;
}
.page-slide-exit {
  transform: translateX(0);
}
.page-slide-exit-active {
  transform: translateX(-100%);
  transition: transform 300ms ease-out;
}

内容的提问来源于stack exchange,提问作者Mauro Arteaga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 08:54:16