猿问

如果同一组件有许多路由,history.push 和 Link 会更改 URL,并且不会重新呈现组件

// the routes here

<Switch>

     <Route exact path='/:page' component={Dashboard} />


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

</Switch>

如果我使用 (history.push) 或 (Link) 只是 URL 更改而不重新加载,我想从第一条路线转到第二条路线。


此外,如果我想从第二条路线到自身但使用新参数,也会出现同样的问题。


//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",


梦里花落0921
浏览 205回答 2
2回答

暮色呼如

当你使用 react-router-dom 时,你不应该使用 history.push()。尝试使用 Redirect from react-router-dom 代替。只需使用名为 redirect 的状态并将其设置为您想要使用函数的新路由:onClick={() => this.setState({ redirect: 'newpath' }};然后像这样在你的渲染中放一个 return:if (this.state.redirect) {&nbsp; &nbsp; return <Redirect to={this.state.redirect} />;}return (&nbsp; &nbsp; ...rest of your render);

侃侃无极

我对 React 以及它周围的很多东西都是危险的新手,但我自己在最后一天一直在努力解决这个问题。因此,这可能是非常糟糕的建议,原因有很多。但这是我的情况,也是我如何让它发挥作用的。function newSongRedirect() {&nbsp; &nbsp; history.push("/SongDetail/0");&nbsp; &nbsp; history.go(0);}并将其连接到我的按钮:<button onClick={() => newSongRedirect() } >New Song</button>似乎 history.push 将值添加到历史记录中,但不会导致对其进行操作。作为现在的第一个项目,history.go(0)然后使其对其进行操作。我已经看到一些帖子引用了 history.push 如果你嵌套在 a 中就不能使用<BrowserRouter>,但在我的情况下,试图在我的 index.js 中替换它只会导致其他问题。另外,我发现这篇文章是从看起来是 React 路由器团队的一员中找到的。当他们有机会时,似乎 useHistory 挂钩将被替换。注意:useHistory 钩子是我们正在研究的未来钩子的快速权宜之计:useNavigate。useNavigate 将提供一个更紧密地对齐的 API,并将解决一些直接在路由器中使用历史 API 的长期问题(它可能看起来很像 @reach/router 的导航 API)。我们现在提供 useHistory 以尽可能轻松地迁移使用历史 API 的现有代码。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答