1.配置动态路由 app.js
<Route path="/detail/:id" component={Detail}></Route>
2.跳转 —this.props.history.push
<Button onClick={this.handleToggle}>detail</Button>
handleToggle=()=>{
this.props.history.push(`/detail/${this.state.id}`)
}
3.详情页面接收 —this.props.match.params
componentDidMount() {
console.log(this.props.match.params) //取到的是对象
consle.log(this.props.match.params.id) //可以直接取到id
}
4.例题 传id去详情页发送请求
4.1配置动态路由
<Route path="/musicdetail/:id" component={MusicDetail}></Route>
4.2首页通过事件传递参数给详情页
import React, { Component } from 'react';
class Music extends Component {
constructor(props){
super(props);
this.state={
playlists:[],
id:""
}
}
render() {
return (
<div className="container">
{this.state.playlists.map(item=>{
return(<div className="list" key={item.id}
onClick={this.handleClick.bind(this,item.id)}> //通过事件传参将id传过去
<img className="pic" src={item.coverImgUrl}></img>
<p className="title">{item.name}</p>
</div>)
})}
</div>
);
}
componentDidMount() {
var url='https://music.aityp.com/top/playlist?cat=韩语';
this.$http.get(url).then(res=>{
var playlists=res.data.playlists;
this.setState({
playlists
})
})
}
handleClick=(id)=>{
this.props.history.push(`/musicdetail/${id}`)
}
}
export default Music;
4.3详情页接收传递过来的参数 this.props.match.params
componentDidMount(){
var id=this.props.match.params.id; //接收id
this.$http.get(`https://music.aityp.com/playlist/detail?id=${id}`).then(res=>{
...
})
}