技术:
react@18
react-router-dom v6 // 前端路由插件
react-transition-group // 动画插件
lazy // 路由懒加载
问题
在react中,我使用路由来完成一个路由切换的动画效果,但是因为路由懒加载的配置,导致我在第一次刷新页面时后续进行第一次跳转,会在造成,新的路由页面出来后,旧的路由页面不消失,把新的路由页面给覆盖住了。
代码如下:
router.js
import { lazy } from 'react' import { Navigate } from 'react-router-dom' import { AuthRoute } from '../components/AuthRoute' // 懒加载路由需要放到普通路由最下面 import NotFound from '../pages/notFound' import Login from '../pages/Login' import Layout from '../pages/Layout' import Books from '../pages/Layout/books' import Shelf from '../pages/Layout/shelf' // const Login = lazy(() => import('../pages/Login')) // const Layout = lazy(() => import('../pages/Layout')) // const Books = lazy(() => import('../pages/Layout/books')) // const Shelf = lazy(() => import('../pages/Layout/shelf')) const routerList = [ { path: '/', element: <Navigate to="/home" /> }, { path: '/login', element: <AuthRoute><Login /></AuthRoute> }, { path: '/home', element: <AuthRoute><Layout></Layout></AuthRoute>, children: [ { index: true, element: <Navigate to="books" /> }, { path: 'books', element: <Books /> }, { path: 'shelf', element: <Shelf /> }, ] }, { path: '*', element: <NotFound /> } ] export default routerList
App.js
import { useLocation, useRoutes } from 'react-router-dom' import { CSSTransition, TransitionGroup } from 'react-transition-group' import routerList from './router' function App() { let location = useLocation(); let router = useRoutes(routerList, location); return ( <div className="App"> {/* <Suspense fallback={ <div style={{ textAlign: 'center', marginTop: 200 }} > loading... </div> }> */} {/* 使用路由懒加载会造成,在刷新完页面后进行第一次跳转页面,旧页面不消失的问题 */} {/* */} <TransitionGroup > <CSSTransition key={location.key} timeout={1000} classNames="fds"> {router} </CSSTransition> </TransitionGroup> {/* </Suspense> */} </div> ); } export default App;
目前还没找到解决方法,只能先将路由懒加载去掉了。
如果有解决办法,请在下方留言!