react-router-dom useNavigate() 挂钩,id 未在 url 路径中设置
react-router-dom useNavigate() hook, id is not getting set in url path
I am using react-router-dom v6 for routing purpose. What I am trying to do is passing id in navigate url path
以下是我的onClick方法和按钮代码
let navigate = useNavigate();
const routeChange = (id) => {
let path = `${PATH_DASHBOARD.general.ViewActivity}` + id;
navigate(path);
};
---------------------------------------------------------------------------
<Button
type="submit"
variant="contained"
sx={{
width: "100%",
marginTop: 3,
}}
onClick={() =>
routeChange(item.id)
}
>
<Typography variant="body2" align="center">
View
</Typography>
</Button>
这是我的 index.js,我正在使用 useRoutes 钩子
{
path: "other",
element: (
<AuthGuard>
<DashboardLayout />
</AuthGuard>
),
children: [
{
path: `/my-activities`,
element: <MyActivities />,
},
{
path: `/my-activities/view-activity/:id`,
element: ({ id }) => <ViewActivity id={id} />,
},
],
}
但是当我尝试访问 url 是浏览器点击按钮时,我得到这个
http://localhost:3000/other/my-activities/view-activity/:id252515
有人知道解决方法吗?
您只是在路径末尾添加了 id
值,您应该替换它
let path = PATH_DASHBOARD.general.ViewActivity.replace(':id',id);
您只是在路径字符串的末尾附加了一个 id
值。
使用 generatePath
实用程序将 id
值注入 path: "/my-activities/view-activity/:id"
路径字符串。
import { generatePath, useNavigate } from 'react-router-dom';
...
const navigate = useNavigate();
const routeChange = (id) => {
const path = generatePath(PATH_DASHBOARD.general.ViewActivity, { id });
navigate(path);
};
I am using react-router-dom v6 for routing purpose. What I am trying to do is passing id in navigate url path
以下是我的onClick方法和按钮代码
let navigate = useNavigate();
const routeChange = (id) => {
let path = `${PATH_DASHBOARD.general.ViewActivity}` + id;
navigate(path);
};
---------------------------------------------------------------------------
<Button
type="submit"
variant="contained"
sx={{
width: "100%",
marginTop: 3,
}}
onClick={() =>
routeChange(item.id)
}
>
<Typography variant="body2" align="center">
View
</Typography>
</Button>
这是我的 index.js,我正在使用 useRoutes 钩子
{
path: "other",
element: (
<AuthGuard>
<DashboardLayout />
</AuthGuard>
),
children: [
{
path: `/my-activities`,
element: <MyActivities />,
},
{
path: `/my-activities/view-activity/:id`,
element: ({ id }) => <ViewActivity id={id} />,
},
],
}
但是当我尝试访问 url 是浏览器点击按钮时,我得到这个
http://localhost:3000/other/my-activities/view-activity/:id252515
有人知道解决方法吗?
您只是在路径末尾添加了 id
值,您应该替换它
let path = PATH_DASHBOARD.general.ViewActivity.replace(':id',id);
您只是在路径字符串的末尾附加了一个 id
值。
使用 generatePath
实用程序将 id
值注入 path: "/my-activities/view-activity/:id"
路径字符串。
import { generatePath, useNavigate } from 'react-router-dom';
...
const navigate = useNavigate();
const routeChange = (id) => {
const path = generatePath(PATH_DASHBOARD.general.ViewActivity, { id });
navigate(path);
};