繁体   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