英文:
How to set default route parameter value in react router?
问题
Sure, here is the translated code snippet:
export const router = createBrowserRouter([
{
path: '/admin',
element: <App/>,
errorElement: <PageError/>,
children: [
{
index: true,
path: 'schedule/:date?',
element: <React.Suspense fallback={<Loading />}>
<PageCalendar />
</React.Suspense>,
},
And the desired behavior you mentioned:
基本上,我希望如果用户尝试打开 "/admin" 或 "/admin/schedule" 页面,则打开 "/admin/schedule/2023-05-11"(当前日期)页面。
英文:
I want to prevent additional redirect. Is there a way to set default parameter value in router config?
export const router = createBrowserRouter([
{
path: '/admin',
element: <App/>,
errorElement: <PageError/>,
children: [
{
index: true,
path: 'schedule/:date?',
element: <React.Suspense fallback={<Loading />}>
<PageCalendar />
</React.Suspense>,
},
Basically I want "/admin/schedule/2023-05-11"
(current date) page to open if user tries to open "/admin"
or "/admin/schedule"
page.
答案1
得分: 1
我不相信没有重定向到某个地方就能完成这个任务,以使UI与浏览器中的正确URL路径同步。
你可以包含一个“catch-all”路由,将当前日期注入并重定向到默认路由。
示例:
import { Navigate, generatePath } from 'react-router-dom';
const ScheduleRedirect = () => {
const date = /* 计算格式化日期,例如"2023-05-11" */
return (
<Navigate
to={generatePath("/admin/schedule/:date", { date })}
replace
/>
);
};
export const router = createBrowserRouter([
{
path: '/admin',
element: <App/>,
errorElement: <PageError/>,
children: [
{
path: 'schedule/:date',
element: (
<React.Suspense fallback={<Loading />}>
<PageCalendar />
</React.Suspense>
),
},
],
},
{
path: "*",
element: <ScheduleRedirect />,
},
]);
英文:
I don't believe there's a way to accomplish this without a redirect somewhere to get the UI synchronized with the correct URL path in the browser.
You can include a "catch-all" route that injects the current date and redirects to the default route.
Example:
import { Navigate, generatePath } from 'react-router-dom';
const ScheduleRedirect = () => {
const date = /* compute formatted date, e.g. "2023-05-11" */
return (
<Navigate
to={generatePath("/admin/schedule/:date", { date })}
replace
/>
);
};
export const router = createBrowserRouter([
{
path: '/admin',
element: <App/>,
errorElement: <PageError/>,
children: [
{
path: 'schedule/:date',
element: (
<React.Suspense fallback={<Loading />}>
<PageCalendar />
</React.Suspense>
),
},
],
},
{
path: "*",
element: <ScheduleRedirect />,
},
]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论