Я пытаюсь использовать кеширование Material-UI с реакции-маршрутизатором.Как я могу программно определить текущий маршрут.
На веб-сайте Material-UI есть пример того, как его использовать, но он требует использования статического breadcrumbNameMap.Я уже пытался разделить путь с помощью HOC "withRouter", но он не работает.
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import { Breadcrumbs, Link, Paper, Typography} from "@material-ui/core";
import { withRouter } from "react-router-dom";
import { useTranslation } from "../Translate";
const useStyles = makeStyles(theme => ({
root: {
justifyContent: "center",
flexWrap: "wrap",
},
paper: {
padding: theme.spacing(1, 2),
},
}));
const breadcrumbNameMap = {
"/inbox": "Inbox",
"/inbox/important": "Important",
"/trash": "Trash",
"/spam": "Spam",
"/drafts": "Drafts",
};
function SimpleBreadcrumbs(props) {
const classes = useStyles();
console.log("Breadcrumbs", props);
const { location } = props;
const pathnames = location.pathname.split("/").filter(x => x);
console.log("pathnames", pathnames);
return (
<div className={classes.root}>
<Paper elevation={0} className={classes.paper}>
<Breadcrumbs aria-label="Breadcrumb">
<Link color="inherit" href="/">
Home
</Link>
{pathnames.map((value, index) => {
const last = index === pathnames.length - 1;
const to = `/${pathnames
.slice(0, index + 1)
.join("/")}`;
console.log("last", last, "to", to);
const path = value.split("-");
console.log("path", path);
// Convert first char of string to uppercase
path.forEach((item, i) => {
// Only capitalize starting from the second element
if (i > 0) {
path[i] =
path[i].charAt(0).toUpperCase() +
path[i].slice(1);
}
});
// return (
// <Typography color="textPrimary" key={to}>
// {useTranslation(path.join(""))}
// </Typography>
// );
// // return (
// // <Typography color="textPrimary" key={to}>
// // {pathnames[to]}
// // </Typography>
// // );
return last ? (
<Typography color="textPrimary" key={to}>
{breadcrumbNameMap[to]}
</Typography>
) : (
<Link color="inherit" to={to} key={to}>
{useTranslation(path.join(""))}
</Link>
);
})}
</Breadcrumbs>
</Paper>
</div>
);
}
export default withRouter(SimpleBreadcrumbs);
Если URL в моем браузере указывает на "http://example.com/level1/level2",, я ожидал, что результат будетиз хлебных крошек будет:
Home / Level1 / Level2
Если URL в браузере будет "http://example.com/level1/",, я бы ожидал:
Home /Уровень 1
Перевод также может быть добавлен позже.Я включил его для показа моего окончательного ожидаемого результата.