react切换路由时url重复的问题

问题描述

我在父组件中用了props.history.push()控制跳转,<Route>设置了exact精确匹配,但是子路由跳转时,url上会重复添加index,每点击一次菜单栏跳转一次,url就会增加一个index, 页面是正常显示的,如图:
react切换路由时url重复的问题react切换路由时url重复的问题

目录结构:

├── src

├──── pages

├───── AdminIndex.js

├───── AddArticle.js

├───── ArticleList.js

├───── Main.js

├──── index.js

index.js

import React from 'react';

import ReactDOM from 'react-dom';

import Main from './pages/Main';

ReactDOM.render(

<React.StrictMode>

<Main />

</React.StrictMode>,

document.getElementById('root')

);

pages/AdminIndex.js

function AdminIndex(props) {

const handleClickArticle = e => {

console.log(e.item.props)

if (e.key == 'addArticle') {

props.history.push('index/add')

} else {

props.history.push('index/list')

}

}

return (

<Layout style={{ minHeight: '100vh' }}>

<Sider>

<div className="logo" />

<Menu>

<Menu.Item>

工作台

</Menu.Item>

<SubMenu key="sub1" title="文章管理" onClick={handleClickArticle}>

<Menu.Item key="addArticle">添加文章</Menu.Item>

<Menu.Item key="articleList">文章列表</Menu.Item>

</SubMenu>

</Menu>

</Sider>

<Layout>

<Content>

<div className="site-layout-background">

<div>

<Route path="/index/" exact component={AddArticle}></Route>

<Route path="/index/add" exact component={AddArticle}></Route>

<Route path="/index/add/:id" exact component={AddArticle}></Route>

<Route path="/index/list" exact component={ArticleList}></Route>

</div>

</div>

</Content>

</Layout>

</Layout>

);

}

export default AdminIndex;

Main.js

import React from 'react';

import { BrowserRouter as Router, Route } from 'react-router-dom'

function Main() {

return (

<Router>

<Route path="/" exact component={Login}/>

<Route path="/index/" component={AdminIndex}/>

</Router>

)

}

export default Main

最近才开始学react,求大佬指教,望轻喷。。

回答

我记得好像是 push 里的路由前面要加上/
就是这样

变更前

props.history.push('index/add')

变更后

props.history.push('/index/add')

以上是 react切换路由时url重复的问题 的全部内容, 来源链接: utcz.com/a/83962.html

回到顶部