繁体   English   中英

命名路径在react-router-dom react js中不起作用

[英]named path not working in react-router-dom react js

我正在使用react-router-dom进行路由。 这是我的代码:

 //Libraries import React from 'react'; import { Tabs, Tab } from 'react-tabify'; import { connect } from 'react-redux'; import { BrowserRouter as Router, Route, withRouter } from 'react-router-dom'; //Components import HomePage from './containers/HomePage'; import PersonsPage from './containers/PersonsPage'; const App = () => ( <Router> <div style={{height: '100%', width: '100%'}}> <Route exact path="/" component={HomePage}/> <Route exact path="/:id" component={PersonsPage}/> // here i want to use like this --> <Route exact path="/personPage/:id" component={PersonsPage}/> </div> </Router> ) export default withRouter(connect()(App)); 

Route exact path="/:id" component={PersonsPage}/> ,但是此Route exact path="/personPage/:id" component={PersonsPage}/>不适用于我。 有人可以从这个例子中澄清/帮助我吗

我认为您应该将路由器包装在Switch组件中。 但是请记住将<Route exact path="/:id" component={PersonsPage}/>最后。

这里在一个文件中有一个示例:

import React, { Component } from 'react';
import { render } from 'react-dom';
import {
  BrowserRouter as Router,
  Route,
  Switch,
  Link,
  withRouter
} from 'react-router-dom';

const HomePage = () => (
  <div>
    <h1>HomePage</h1>
    <ul>
      <li><Link to="/user/Tom">Tom</Link></li>
      <li><Link to="/user/John">John</Link></li>
      <li><Link to="/user/Andy">Andy</Link></li>
    </ul>
  </div>
);

const PersonsPage = (props) => (
  <div>
    <h1>Profile: {props.match.params.name}</h1>
  </div>
);

class App extends Component {
  render() {
    return (
      <Switch>
        <Route exact path="/" component={HomePage}/>
        <Route exact path="/user/:name" component={PersonsPage}/>
      </Switch>
    );
  }
}

const AppWithRouter = withRouter(App);

render(
  <Router>
    <AppWithRouter />
  </Router>
  , document.getElementById('root')
);

在这里,您可以链接到工作版本https://stackblitz.com/edit/react-qqpraz

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM