react-router-dom v6 参数只有数字

react-router-dom v6 params only numbers

我想在 react-router-dom v6 的 may 参数中添加数字正则表达式。它在 v5 中像这样工作:

 <Route path="list/:id(\d+)" element={<MyComponent/>} /> 

但它在 v6 中不起作用。

react-router-dom@6 中不支持正则表达式。

What Happened to Regexp Routes Paths?

Regexp route paths were removed for two reasons:

  1. Regular expression paths in routes raised a lot of questions for v6's ranked route matching. How do you rank a regex?

  2. We were able to shed an entire dependency (path-to-regexp) and cut the package weight sent to your user's browser significantly. If it were added back, it would represent 1/3 of React Router's page weight!

您可以使用 useParams 挂钩并测试组件中的 id 参数。

示例:

import { useParams, useNavigate } from 'react-router-dom';

const MyComponent = () => {
  const { id } = useParams();
  const navigate = useNavigate();

  useEffect(() => {
    if (!/\d+/.test(id)) {
      navigate(-1);
    }
  }, [id, navigate]);

  ...
};