一、react-router

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

二、路由跳转和get传值

2-1 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. }

2-2 事件跳转 this.props.history.push()

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

2-3 query-string解析get传值

  1. //Detail.js
  2. //this.props.location.search
  3. //安装依赖
  4. yarn add query-string
  5. import queryString from 'query-string'
  6. class Detail extends Component {
  7. ...
  8. componentDidMount() {
  9. var url = this.props.location.search;
  10. console.log(queryString.parse(url))
  11. }
  12. }
  13. export default Detail;

三、动态路由

  1. 5-1 配置动态路由
  2. <Route path="/detail/:id" component={Detail}></Route>
  3. 5-2 跳转
  4. <Button onClick={this.handleToggle}>detail</Button>
  5. handleToggle=()=>{
  6. this.props.history.push(`/detail/${this.state.id}`)
  7. }
  8. 5-3 详情页接收 this.props.match.params
  9. componentDidMount() {
  10. console.log(this.props.match.params)
  11. }