0

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}/>对我不起作用。有人可以澄清/帮助我吗?

4

1 回答 1

1

我认为您应该简单地将路由器包装在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

于 2017-10-24T10:50:49.220 回答