英文:
react router v6 loader not called while using useNavigate() hook
问题
尝试使用在react router v6
中定义的useNavigate()
钩子时,我无法弄清楚为什么在我的路由级别定义的加载程序即使重定向正确也不会被调用。
值得注意的是,使用链接访问路由会正确触发加载程序。
我的路由定义:
...
{
path: "differences",
loader: async () => {
return loadPractitionersWithDifferences();
}, // <===== 未被调用
element: <Differences />,
children: [
{
path: ":id",
loader: async ({ params }) => {
return loadDifferenceForPractitioner(params.id);
},
element: <Difference />
}
]
};
...
useNavigate
钩子:
const navigate = useNavigate();
const saveDecisions = () => {
return axios
.post("/practitioners/saveDecisions", pra)
.then(navigate("/differences"));
};
英文:
Trying to use the useNavigate()
hook as defined in react router v6
, i cannot figure out why loader defined at my route level is not called even if the redirection is done correctly.
It's worth to notice than using a link to access the route is triggering loader correctly.
My route definition :
...
{
path: "differences",
loader: async () => {
return loadPractitionersWithDifferences();
}, //<===== not called
element: <Differences />,
children: [
{
path: ":id",
loader: async ({ params }) => {
return loadDifferenceForPractitioner(params.id);
},
element: <Difference />
}
]
};
...
The useNavigate
hook :
const navigate = useNavigate();
const saveDecisions = () => {
return axios
.post("/practitioners/saveDecisions", pra)
.then(navigate("/differences"));
};
答案1
得分: 2
你不能直接在 then
中直接编写 navigate
函数,像这样。then
期望的参数是在 promise 完成时将被调用的函数。在你提供的代码中,navigate 可能会在代码加载时立即触发。
你必须传递一个将调用 navigate
的匿名函数:
const saveDecisions = () => {
return axios
.post('/practitioners/saveDecisions', pra)
.then(() => navigate('/differences'));
}
英文:
You can't write the navigate
function in a then
directly like this. The argument expected by then
is the function that will be called when the promise is fulfilled. In the code you provided, the navigate is probably triggered immediately when your code is loaded.
You have to pass an anonymous function that will call navigate
:
const saveDecisions = () => {
return axios
.post('/practitioners/saveDecisions', pra)
.then(() => navigate('/differences'));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论