Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

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,求大佬指教,望轻喷。。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

变更前

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

变更后

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...