简体   繁体   English

如果替换路径中的最后一个元素,React Router v6 useNavigate() 不会导航

[英]React Router v6 useNavigate() doesn't navigate if replacing last element in path

I have a react component with the following function我有一个具有以下功能的反应组件

    const handleNavigate = (clientId) => {
        console.log(clientId)
        navigate(`/dashboard/clients/${clientId}`)
    }

The console.log() is showing the ID I want to append to use in the navigate function. console.log() 显示了我要附加以在导航功能中使用的 ID。
AND
The URL in the browser is updating.浏览器中的 URL正在更新。

But the page does not change.但是页面没有变化。

This works to navigate from /dashboard/clients to /dashboard/clients/foo这可以从/dashboard/clients导航到/dashboard/clients/foo

but it does not work to navigate from /dashboard/clients/foo to /dashboard/clients/bar但从/dashboard/clients/foo导航到/dashboard/clients/bar不起作用

The clientId is passed into the card like so... clientId 像这样传递到卡中......

const CompanyCard = (props) => {
    const { client, showWatchlist, removeDisabled, showRemove, removeType } = props
...
}

then in the card然后在卡里

                <CardActionArea
                    onClick={() => handleNavigate(client._id)}
                 ...

Any ideas?有任何想法吗?
Thanks谢谢

UPDATE更新

After reading up from @redapollos suggestion I tried Outlet and the在阅读了@redapollos 的建议后,我尝试了Outlet

useRoutes methods... neither worked. useRoutes 方法...都不起作用。

import { useRoutes } from 'react-router-dom'

// then in the routes...

        { path: 'clientdetail/:id', element: <ClientDetail /> },
        { path: 'clientdetail/', element: <ClientDetail /> },

This might be due to using the useRoutes hook but I am still working on it.这可能是由于使用了useRoutes挂钩,但我仍在努力。

Another question here on SO that might get an answer sooner - https://stackoverflow.com/a/70009104/13078911 SO上的另一个问题可能会很快得到答案 - https://stackoverflow.com/a/70009104/13078911

Try replacing the URL instead of adding a new one.尝试替换 URL 而不是添加新 URL。 when you are going from /dashboard/clients to /dashboard/clients/foo you are going from a parent to a child, your URL has everything plus /foo .当您从/dashboard/clients转到/dashboard/clients/foo时,您将从父母转到孩子,您的 URL 包含所有内容以及/foo But, when you are going from /dashboard/clients/foo to /dashboard/clients/bar you are navigating to a sibling /foo to /bar that might be causing the issue.但是,当您从/dashboard/clients/foo转到/dashboard/clients/bar时,您正在导航到可能导致问题的兄弟/foo/bar try to replace the value like navigate(/dashboard/clients/ba, {replace: true}) here is example of how to use this in general.尝试替换像navigate(/dashboard/clients/ba, {replace: true})这样的值,这是一般如何使用它的示例。 use it for more information.使用它来获取更多信息。 https://www.digitalocean.com/community/tutorials/react-react-router-v6 https://www.digitalocean.com/community/tutorials/react-react-router-v6

I had this same issue and my code was fine, however, I found out at this post that optional params aren't supported in v6.我遇到了同样的问题,我的代码很好,但是,我在这篇文章中发现 v6 不支持可选参数。
https://github.com/remix-run/react-router/issues/7285 https://github.com/remix-run/react-router/issues/7285

I had:我有:

<Routes>
  <Route path="list/:id?" element={<SystemList />} />
</Routes>

and had to change it to:并不得不将其更改为:

<Routes>
  <Route path="list/:id" element={<SystemList />} />
  <Route path="list/" element={<SystemList />} />
</Routes>

I'm hoping they support it in the future but as of v6.0.2 they do not.我希望他们将来支持它,但从 v6.0.2 开始,他们不支持。

Workable solution!可行的解决方案!

navigate('/url')
navigate(0)

After replacing the url, manually calling navigate(0) will refresh the page automatically!替换url后,手动调用navigate(0)会自动刷新页面!

This will work in a situation like navigate from /same_path/foo to /same_path/bar .这将适用于从/same_path/foo导航到/same_path/bar的情况。

Be aware of unintended page referesh behavior:请注意意外的页面引用行为:

For a normal situation like navigate from /home to /same_path/bar , navigate(0) will cause page to refresh even after page has finished rendering.对于像从/home导航到/same_path/bar这样的正常情况,即使页面完成渲染, navigate(0)也会导致页面刷新。 And to prevent that, you can take a look at this question .为了防止这种情况,你可以看看这个问题

More info:更多信息:

  1. useNavigate docs使用导航文档

  2. How do I reload a page with react-router?如何使用 react-router 重新加载页面?

也许尝试组件导航:

<Navigate to={<your_path>}/>

I just read in React Router Dom Docs v6 this solution:我刚刚在 React Router Dom Docs v6 中阅读了这个解决方案:

import { useNavigate } from 'react-router-dom';
...
const navigate = useNavigate();
...
<Button onClick={() => navigate('../user', { replace: true })}>Register</Button>

So, basically I added ../ before the route and the replace: true .所以,基本上我在 route 和replace: true之前添加了../
Reference: https://reactrouter.com/docs/en/v6/hooks/use-navigate参考: https ://reactrouter.com/docs/en/v6/hooks/use-navigate

It worked for me, hope it works for u!它对我有用,希望它对你有用! (: (:

I think this is a better work around on this one.我认为这是一个更好的解决方法。

import React from 'react' 
import { useHistory } from 'react-router-dom' 
... 

const history = useHistory() 
const handleNavigate = (clientId) => {
        console.log(clientId)
        history.push(`/dashboard/clients/${clientId}`)
    }

Make sure your app is wrapped in a BrowserRouter from react-router-dom确保您的应用程序包含在来自react-router-domBrowserRouter

Try adding window-location as key prop to the element in route尝试将窗口位置作为关键道具添加到路由中的元素

ie IE

<Route path=":id" element={ <Hello key={window.location.pathname} } />

Based on this link https://github.com/remix-run/react-router/issues/8245 I could solve this issue.基于这个链接https://github.com/remix-run/react-router/issues/8245我可以解决这个问题。

I guess that as nothing has been changed the screen is not updated.我想因为没有任何改变,所以屏幕没有更新。 As soon as I added I useEffect on the target route component and passed the lastelement as a parameter it worked.一旦我在目标路由组件上添加了 useEffect 并将 lastelement 作为参数传递它就可以了。

In other words: On the target component add: Reac.useEffect(....) [lastElement].换句话说:在目标组件上添加:Reac.useEffect(....) [lastElement]。

This might be a little late but I had the same issue and you simply just have to trigger a re-render for your component.这可能有点晚了,但我遇到了同样的问题,您只需触发组件的重新渲染。 You can do this by adding a useEffect hook within your component you have assigned /dashboard/clients/:clientId to with a dependency of the param you want to update.您可以通过在您已分配/dashboard/clients/:clientId的组件中添加一个 useEffect 挂钩来执行此操作,并具有您要更新的参数的依赖项。

It should look something like this:它应该看起来像这样:

import React, { useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom';


const ClientDashboard = () => {

    const params = useParams()
    const navigate = useNavigate()

    useEffect(() => {
    //do something with new id 
    },[params.clientId])

    const handleNavigate = (clientId) => {
        navigate(`/dashboard/clients/${clientId}`)
    }

    .....
}

Your page should now update with the new param您的页面现在应该使用新参数更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM