我有一个包含从categoriesData 组件中提取的类别的页面。我将“名称”存储在网址名称和标签中。问题是我希望 url 包含不带变音符号的名称 http://localhost:3000/sortiment/substraty 和带变音符号的名称 - “substráty”。
CategoryPage.js:
const CategoryPage = () => {
const { categoryName } = useParams();
const category = categoriesData.find((c) => c.name === categoryName);
if (!category) {
return (
<div>
<h1>Category not found</h1>
<Link to="/sortiment">Back to Sortiment</Link>
</div>
);
}
return (
<h1 className="uppercase text-headerGreen font-bold text-2xl text-center xl:text-start">
{category.name}
</h1>
);
};
categoriesData.js:
const categoriesData = [
{
name: "substráty",
URLname: "substraty",}]
function App() {
return (
<>
<Router>
<Routes>
<Route
path="/sortiment/:categoryName"
element={<CategoryPage />}
/>
</Routes>
</Router>
</>
);
}
嗨,伙计,您使用以下函数来删除变音符号。
const removeDiacritics = (str) => {
return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}
我正在更新您的代码以获得更多理解:
const CategoryPage = () => {
const { categoryName } = useParams();
const categoryNameWithoutDiacritics = removeDiacritics(categoryName);
const category = categoriesData.find((c) => removeDiacritics(c.name) === categoryNameWithoutDiacritics);
if (!category) {
return (
<div>
<h1>Category not found</h1>
<Link to="/sortiment">Back to Sortiment</Link>
</div>
);
}
return (
<h1 className="uppercase text-headerGreen font-bold text-2xl text-center xl:text-start">
{category.name}
</h1>
);
};