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

问题描述

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

目录结构:
├── 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,求大佬指教,望轻喷。。

阅读 4.5k
1 个回答

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

变更前

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

变更后

props.history.push('/index/add')
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏