![](/img/trans.png)
[英]Uncaught Error: [Elements] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
[英]Uncaught Error: [RouteWrapper] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
我正在使用 React Router v6 并为我的应用程序创建私有路由。
在文件 Route.js 中,我有代码
export default function RouteWrapper({
element: Element,
isPrivate,
...rest
}) {
const { signed, loading } = useContext(AuthContext);
if (loading) {
return <div></div>;
}
if (!signed && isPrivate) {
return <Navigate to="/" />;
}
if (signed && !isPrivate) {
return <Navigate to="/dashboard" />;
}
return <Route {...rest} render={(props) => <Element {...props} />} />;
}
在文件 index.js 中,我写成:
return (
<Routes>
<Route path="/" element={SignIn} />
<Route path="/register" element={SignUp} />
<Route path="/dashboard" element={Dashboard} isPrivate />
<Route path="/profile" element={Profile} isPrivate />
<Route path="/customers" element={Customers} isPrivate />
<Route path="/new" element={New} isPrivate />
<Route path="/new/:id" element={New} isPrivate />
</Routes>
);
}
有什么我想念的吗?
你应该转换
<Routes>
<Route exact path="/" element={Dashboard} />
</Routes>
至
<Routes>
<Route exact path="/" element={<Dashboard/>} />
</Routes>
此外,如果您想让您的 UI 与 URL 保持同步,请像这样使用。
<BrowserRouter>
<Routes>
<Route exact path="/" element={<Dashboard/>} />
</Routes>
</BrowserRouter>
最好的。
RouteWrapper
不是Route
组件,并且无法通过react-router-dom
进行不变检查。RouteWrapper
直接渲染一个Route
组件,如果第一个不变量没有失败,则会触发另一个不变量违规。 在构建嵌套路由的情况下, Route
组件只能由Routes
组件或其他Route
组件直接渲染。 简而言之,在react-router-dom@6
中不再支持自定义路由组件。 您应该改为使用包装器组件/布局路由来处理此用例。
将RouteWrapper
转换为包装器组件,该组件为要渲染的嵌套路由组件呈现Outlet
组件。
例子:
import { Navigate, Outlet } from 'react-router-dom';
export default function RouteWrapper({ isPrivate }) {
const { signed, loading } = useContext(AuthContext);
if (loading) {
return <div></div>;
}
if (!signed && isPrivate) {
return <Navigate to="/" />;
}
if (signed && !isPrivate) {
return <Navigate to="/dashboard" />;
}
return <Outlet />; // <-- nested routes render here
}
使用RouteWrapper
包装您要保护的路由。
return (
<Routes>
<Route element={<RouteWrapper />}>
<Route path="/" element={<SignIn />} />
<Route path="/register" element={<SignUp />} />
</Route>
<Route element={<RouteWrapper isPrivate />}>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/profile" element={<Profile />} />
<Route path="/customers" element={<Customers />} />
<Route path="/new" element={<New />} />
<Route path="/new/:id" element={<New />} />
</Route>
</Routes>
);
有关详细信息,请参阅布局路线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.