react - router - dom, 原生 的 没有什么 next 框架之类的,那路由怎么弄,我tm这弄了半天

其实应该用 👇 


  
import { useNavigate } from 'react-router-dom';
  const navigate = useNavigate();

histroy已经是过去式了。navigate xxx就行

但是他会报个错,必须要router包裹,

然后我是想有个Layout套外面,菜单也放在最外面,切换的时候只是切换里面,但是不能 <Layout> <RouterProvider router={router} /></Layout>, 这样会说 Error: useNavigate() may be used only in the context of a <Router> component.

而是 用根路由和children吧,

{
    path: '/',
    element: <Layout children={undefined} />, // 将 Layout 作为根路由
    children: [
      {
        index: true,
        element: <Navigate to="/aaaa" replace />,
      },

这也不好, 哪能 / 做主路由, /后面的东西做其他路由呢,太怪了。

其实应该把Layout套到路由里,路由还是各自为战,

  {
    path: '/aaaa',
    element: <Layout children={<MomentManage />} />,
  },
  {
    path: '/user-block',
    element: <Layout children={<UserBlock />} />,
  },

— — — — — —- — — — — — — — — — —- — — — — — — — — — —- — — — — — — — — — —- — — — —

Layout要写好一点,

type LayoutProps = {
  children: ReactNode;
};

const Layout = ({ children }: LayoutProps) => {
  return (
    <div className={styles.container}>
      <div className={styles.content}>{children}</div>
    </div>
  );
};

然后router那个,use router这个是next的写法了。

— — — — — —- — — — — — — — — — —- — — — — — — — — — —- — — — — — — — — — —- — — — —

然后我发现还有个问题,就是路由没有就直接404,可以直接写* 放到最后当兜底

— — — — — —- — — — — — — — — — —- — — — — — — — — — —- — — — — — — — — — —- — — — —

直接获取当前路径:给menu回显用。

import {useNavigate} from 'react-router-dom';
 
// 获取当前路由路径
const location = useLocation();
console.log(location.pathname);
— — — — — —- — — — — — — — — — —- — — — — — — — — — —- — — — — — — — — — —- — — — —

获取路由参数

其实这里有两个,emm,。,params时获取不到的。params只是

路由定义 访问 URL useParams() 返回值
<Route path="/users/:id" /> /users/123 { id: "123" }
<Route path="/posts/:slug" /> /posts/hello-world { slug: "hello-world" }
<Route path="/:lang/docs" /> /zh/docs { lang: "zh" }

然后,params时👆 , 正常我们是要用usesearchparams

useParams() 获取路径参数 { id: "123" }
useSearchParams() 获取查询参数(URLSearchParams) ?name=John&age=20
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐