1.Link跳转—get传值
1.1传值
//1.传值
import React, { Component } from 'react';
import {Link} from 'react-router-dom';
import {Button} from 'antd'
class Home extends Component {
constructor(props){
super(props);
this.state={
id:1001
}
}
render() {
return (
<div>
主页
<Link to={`/detail?id=${this.state.id}`}> //传值
<Button>detail</Button>
</Link>
</div>
);
}
}
export default Home;
1.2接收
//2.接收
import React,{Component} from 'react'
//导入query-string模块进行解析
import queryString from 'query-string';
class Detail extends Component {
render(){
return (<div>detail</div>)
}
componentDidMount(){
var url = this.props.location.search;
var obj = queryString.parse(url)
console.log(obj)
}
}
export default Detail;
2.事件跳转 this.props.history.push()
class Home extends Component {
constructor(props){
super(props);
this.state={
id:1001
}
}
render() {
return (
<div>
主页
<Button onClick={this.handleToggle}>detail</Button>
</div>
);
}
handleToggle=()=>{
this.props.history.push(`/detail?id=${this.state.id}`)
}
}
3.query-string解析get传值
因为传过来的是字段,所以要安装query-string将字段转成对象 {id=123456}
//1.安装
yarn add query-string
//2.在detail页面接收 this.props.location.search
import React, { Component } from 'react';
import queryString from 'query-string'
class Detail extends Component {
render() {
return (
<div>
详情页
</div>
);
}
/* cdm */
componentDidMount() {
var url=this.props.location.search;
console.log(queryString.parse(url))
}
}
例题 get传id
首页传id—this.props.history.push
import React, { Component } from 'react';
import './Movie.css'
class Movie extends Component {
constructor(props){
super(props);
this.state={
subjects:[]
}
}
render() {
return (
<div className="container">
{this.state.subjects.map(item=>{
return(<div className="list" key={item.id}
onClick={this.handleClick.bind(this,item.id)}>
<img className="pic" src={item.images.small}></img>
<p className="title">{item.title}</p>
</div>)
})}
</div>
);
}
componentDidMount() {
var url="http://douban.uieee.com/v2/movie/top250"
this.$http.get(url).then(res=>{
var subjects=res.data.subjects;
this.setState({
subjects
})
})
}
handleClick(id){
this.props.history.push(`/moviedetail?id=${id}`)
}
}
export default Movie;
详情页接收—this.props.location.search
//详情页接收id
componentDidMount() {
var id=queryString.parse(this.props.location.search) ; //取到的是对象
console.log(id)
var id=id.id; //取id后面的数据
this.setState({
id
})
this.$http.get(`https://douban-api.uieee.com/v2/movie/subject/${id}`).then(res=>{
...
}
}