1.配置动态路由 app.js

  1. <Route path="/detail/:id" component={Detail}></Route>

2.跳转 —this.props.history.push

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

3.详情页面接收 —this.props.match.params

  1. componentDidMount() {
  2. console.log(this.props.match.params) //取到的是对象
  3. consle.log(this.props.match.params.id) //可以直接取到id
  4. }

4.例题 传id去详情页发送请求

4.1配置动态路由

  1. <Route path="/musicdetail/:id" component={MusicDetail}></Route>

4.2首页通过事件传递参数给详情页

  1. import React, { Component } from 'react';
  2. class Music extends Component {
  3. constructor(props){
  4. super(props);
  5. this.state={
  6. playlists:[],
  7. id:""
  8. }
  9. }
  10. render() {
  11. return (
  12. <div className="container">
  13. {this.state.playlists.map(item=>{
  14. return(<div className="list" key={item.id}
  15. onClick={this.handleClick.bind(this,item.id)}> //通过事件传参将id传过去
  16. <img className="pic" src={item.coverImgUrl}></img>
  17. <p className="title">{item.name}</p>
  18. </div>)
  19. })}
  20. </div>
  21. );
  22. }
  23. componentDidMount() {
  24. var url='https://music.aityp.com/top/playlist?cat=韩语';
  25. this.$http.get(url).then(res=>{
  26. var playlists=res.data.playlists;
  27. this.setState({
  28. playlists
  29. })
  30. })
  31. }
  32. handleClick=(id)=>{
  33. this.props.history.push(`/musicdetail/${id}`)
  34. }
  35. }
  36. export default Music;

4.3详情页接收传递过来的参数 this.props.match.params

  1. componentDidMount(){
  2. var id=this.props.match.params.id; //接收id
  3. this.$http.get(`https://music.aityp.com/playlist/detail?id=${id}`).then(res=>{
  4. ...
  5. })
  6. }

image.png