React Link跳转路径追加而非替换,如何基于根URL跳转?
问题描述
从ViewItemDetails页面跳转至EditItem页面时,新增的Link组件跳转后路径变为http://localhost:3000/ViewItemDetails/1/EditItem/1,期望路径为http://localhost:3000/EditItem/1(替换原有路径而非追加),需要让Link基于根URL“/”跳转而非当前URL。
相关代码
原正常跳转的路由配置
<Router> <Routes> <Route path="/" element={<Layout />}> <Route index element={<App />} /> <Route path="/Wishlists" element={<ItemContainer />} /> <Route exact path="/ViewItemDetails/:id" element={<ViewItemDetails />} /> </Route> </Routes> </Router>
原正常跳转的Item.jsx组件代码
<Link to={`/ViewItemDetails/${props.id}`} state={{ item: props }} className="fill-parent"> </Link>
新增的ViewItemDetails组件内的Link(有问题的代码)
<Link to={`EditItem/${item.id}`} state={{ itemId: item.id }}> <button>Edit Item</button> </Link>
更新后的路由配置
<Router> <Routes> <Route path="/" element={<Layout />}> <Route index element={<App />} /> <Route path="/Wishlists" element={<ItemContainer />} /> <Route exact path="/ViewItemDetails/:id" element={<ViewItemDetails />} /> <Route exact path="/EditItem/:id" element={<EditItem />} /> </Route> </Routes> </Router>
解决方案
问题出在Link组件的to属性路径没有以斜杠/开头,导致生成的是相对当前页面路径的跳转链接,从而出现路径追加的情况。
只需要给to的路径加上开头的斜杠/,将相对路径改为绝对路径即可:
<Link to={`/EditItem/${item.id}`} state={{ itemId: item.id }}> <button>Edit Item</button> </Link>
这样跳转时就会基于根URL/生成目标路径http://localhost:3000/EditItem/1,实现替换原有路径而非追加的效果。
内容的提问来源于stack exchange,提问作者Jake Roberts
相关产品推荐
相关产品推荐

