簡體   English   中英

history.push 和 Link 更改 URL 並且如果我有多個相同組件的路由,則不重新渲染組件

[英]history.push and Link change the URL and not re render the component if I have many routes for the same component

// the routes here
<Switch>
     <Route exact path='/:page' component={Dashboard} />

      <Route exact path='/:subCateg/:categ' component={Dashboard} />
</Switch>

我想 go 從第一條路線到第二條路線,如果我使用(history.push)或(鏈接)只是 URL 更改而不重新加載。

此外,如果我想 go 從第二條路線到自身但使用新參數,也會出現同樣的問題。

//here I'm in Dashbord and the History also pushing to Dashboard
onClick={
        ()=>{
            history.push({pathname:`/${categ}/${subCateg}`, state: {id: subCateg.id}})
                                    // window.location.reload(false);
            }
        }

如您所見,我使用了“window.location.reload(false);” 它解決了加載問題,但是如果我想通過瀏覽器返回按鈕返回,同樣的問題:更改 URL 而不是重新加載。 我也認為使用“window.location.reload(false);” 不是一個好習慣。

`` package.json:“react-router-dom”:“^5.1.2”,

當你使用 react-router-dom 時,你不應該使用 history.push()。 嘗試使用 Redirect from react-router-dom 代替。

只需使用名為 redirect 的 state 並將其設置為您想要的 go 的新路由和您的 function:

onClick={() => this.setState({ redirect: 'newpath' }};

然后像這樣在你的渲染中放一個 return:

if (this.state.redirect) {
    return <Redirect to={this.state.redirect} />;
}
return (
    ...rest of your render
);

警告:我對 React 以及它周圍的很多東西都是危險的新手,但我自己在最后一天一直在努力解決這個問題。 因此,這可能是非常糟糕的建議,原因有很多。 但這是我的情況,也是我如何讓它發揮作用的。

function newSongRedirect() {
    history.push("/SongDetail/0");
    history.go(0);
}

並將其連接到我的按鈕:

<button onClick={() => newSongRedirect() } >New Song</button>

似乎 history.push 將值添加到歷史記錄中,但不會導致對其進行操作。 作為現在的第一個項目, history.go(0)然后使其對其進行操作。

我已經看到一些帖子引用了 history.push 如果您嵌套在<BrowserRouter>中,則無法使用,但在我的情況下,嘗試在我的 index.js 中替換它只會導致其他問題。

另外,我發現這篇文章是從看起來是 React 路由器團隊的一員中找到的。 當他們有機會時,似乎 useHistory 鈎子將被替換。

注意:useHistory 鈎子是我們正在研究的未來鈎子的快速權宜之計:useNavigate。 useNavigate 將提供一個 API,它與直接在路由器中使用歷史 API 更緊密地對齊並將解決一些長期存在的問題(它可能看起來很像 @reach/router 的導航 API)。 我們現在提供 useHistory 以盡可能輕松地遷移使用歷史 API 的現有代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM