未捕获的类型错误:无法读取未定义的属性(读取‘路径名’)且上述错误发生在 <Link> 组件中:
2022-07-31
1097
我正在使用
react-router-dom
v6,但我遵循的是旧教程。我遇到了上述错误,我尝试了很多方法,但仍然遇到相同的错误。
这是产生错误的文件:
import React from "react";
import "./sidebar.css";
import logo from "../../images/logo.png";
import { Link } from "react-router-dom";
import { TreeView, TreeItem } from "@material-ui/lab";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import PostAddIcon from "@material-ui/icons/PostAdd";
import AddIcon from "@material-ui/icons/Add";
import ImportExportIcon from "@material-ui/icons/ImportExport";
const Sidebar = () => {
return (
<div className="sidebar">
<Link to="/">
<img src={logo} alt="Ecommerce" />
</Link>
<Link to="/admin/dashboard">
<p>
Dashboard
</p>
</Link>
<Link>
<TreeView
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ImportExportIcon />}
>
<TreeItem nodeId="1" label="Products">
<Link to="/admin/products">
<TreeItem nodeId="2" label="All" icon={<PostAddIcon />} />
</Link>
<Link to="/admin/product">
<TreeItem nodeId="3" label="Create" icon={<AddIcon />} />
</Link>
</TreeItem>
</TreeView>
</Link>
</div>
);
};
export default Sidebar;
1个回答
您有一个
Link
组件,但没有
to
prop 来包装
TreeView
组件。
to
是必需的属性。
interface LinkProps extends Omit< React.AnchorHTMLAttributes<HTMLAnchorElement>, "href" > { replace?: boolean; state?: any; to: To; // <-- non-optional reloadDocument?: boolean; }
我认为这里的链接没有意义,所以我建议删除它。
示例:
const Sidebar = () => {
return (
<div className="sidebar">
<Link to="/">
<img src={logo} alt="Ecommerce" />
</Link>
<Link to="/admin/dashboard">
<p>Dashboard</p>
</Link>
<TreeView
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ImportExportIcon />}
>
<TreeItem nodeId="1" label="Products">
<Link to="/admin/products">
<TreeItem nodeId="2" label="All" icon={<PostAddIcon />} />
</Link>
<Link to="/admin/product">
<TreeItem nodeId="3" label="Create" icon={<AddIcon />} />
</Link>
</TreeItem>
</TreeView>
</div>
);
};
如果您确实意味着
Link
包装该子菜单的
全部
,那么它需要所需的
to
属性。
Drew Reese
2022-07-31