React Router v6在使用useNavigate()钩子时未调用加载器。

huangapple go评论57阅读模式
英文:

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"));
};

React Router v6在使用useNavigate()钩子时未调用加载器。

英文:

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: &quot;differences&quot;,
  loader: async () =&gt; {
    return loadPractitionersWithDifferences();
  }, //&lt;===== not called
  element: &lt;Differences /&gt;,
  children: [
    {
      path: &quot;:id&quot;,
      loader: async ({ params }) =&gt; {
        return loadDifferenceForPractitioner(params.id);
      },
      element: &lt;Difference /&gt;
    }
  ]
};
...

The useNavigate hook :

const navigate = useNavigate();
const saveDecisions = () =&gt; {
  return axios
    .post(&quot;/practitioners/saveDecisions&quot;, pra)
    .then(navigate(&quot;/differences&quot;));
};

React Router v6在使用useNavigate()钩子时未调用加载器。

答案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 = () =&gt; {
  return axios
    .post(&#39;/practitioners/saveDecisions&#39;, pra)
    .then(() =&gt; navigate(&#39;/differences&#39;));
}

huangapple
  • 本文由 发表于 2023年6月15日 19:22:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76481956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定