我正在尝试反应路由器v6 。根据{{3}},我创建了路由对象并传递给useRoutes()
:
function SomeOtherElement() {
return <h1>add user</h1>;
}
const routes = [
{
path: 'app',
element: <DashboardLayout />,
children: [
{ path: 'account', element: <AccountView /> },
{
path: 'users', element: <UserListView />,
children: [
{ path: 'add', element: <SomeOtherElement /> }
]
},
{ path: 'dashboard', element: <DashboardView /> },
{ path: 'products', element: <ProductListView /> },
{ path: 'settings', element: <SettingsView /> },
{ path: '*', element: <Navigate to="/404" /> }
]
}];
const routing = useRoutes(routes);
但是嵌套路由无效。如您在上面的对象中看到的,我想创建URL并呈现用户“ 添加”功能的UI。
浏览器中的URL已正确更新为 http:// localhost:3000 / app / users / add ,但用户界面未更新。
答案 0 :(得分:1)
如here所述,您需要使用<Outlet />
元素作为子元素(即嵌套路由)的占位符。
示例:
import { Outlet } from 'react-router-dom'
// ...
const routes = [
{
path: "app",
element: (
<>
<DashboardLayout />
<Outlet />
</>
),
children: [
{ path: "account", element: <AccountView /> },
{
path: "users",
element: (
<>
<UserListView />
<Outlet />
</>
),
children: [{ path: "add", element: <SomeOtherElement /> }],
},
{ path: "dashboard", element: <DashboardView /> },
],
},
];
或者您可能想在父组件中包含Outlet
:
export default function DashboardLayout() {
return (
<>
<h1>I am Dashboard Layout</h1>
<Outlet />
</>
);
}