1、安装依赖

yarn add react-router-dom

2、配置路由

App.js

  1. import React, { Component } from 'react';
  2. import {
  3. BrowserRouter as Router,
  4. Switch,
  5. Route,
  6. Link
  7. } from "react-router-dom";
  8. import Home from './views/Home'
  9. import About from './views/About'
  10. class App extends Component {
  11. render() {
  12. return (
  13. <div>
  14. <Router>
  15. <ul>
  16. <li><Link to="/">首页</Link></li>
  17. <li><Link to="/about">About</Link></li>
  18. </ul>
  19. {/* exact路由的严格匹配,只有路径为/才会加载对应的路由 */}
  20. <Switch>
  21. <Route exact path="/" component={Home}></Route>
  22. <Route path="/about" component={About}></Route>
  23. <Route path="/detail" component={Detail}></Route>
  24. </Switch>
  25. </Router>
  26. </div>
  27. );
  28. }
  29. }
  30. export default App;

3、路由跳转和get传值

Home.js

Link跳转

  1. class Home extends Component {
  2. constructor(props){
  3. super(props);
  4. this.state = {
  5. id:1001
  6. }
  7. }
  8. render() {
  9. return (
  10. <div>
  11. 主页
  12. <Link to={`/detail?id=${this.state.id}`}>
  13. <Button>detail</Button>
  14. </Link>
  15. </div>
  16. );
  17. }
  18. }

点击跳转

  1. <Button onClick={this.handleToggle}>detail</Button>
  2. handleToggle=()=>{
  3. this.props.history.push(`/detail?id=${this.state.id}`)
  4. }

4、query-string解析get传值

Detail.js
this.props.location.search
安装依赖 yarn add query-string

  1. import queryString from 'query-string'
  2. class Detail extends Component {
  3. ...
  4. componentDidMount() {
  5. var url = this.props.location.search;
  6. var ids = queryString.parse(url); //这里拿到的id值是一个对象 还要再去解析
  7. var id = ids.id;
  8. }
  9. }
  10. export default Detail;