1、安装依赖
2、配置路由
App.js
import React, { Component } from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import Home from './views/Home'
import About from './views/About'
class App extends Component {
render() {
return (
<div>
<Router>
<ul>
<li><Link to="/">首页</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
{/* exact路由的严格匹配,只有路径为/才会加载对应的路由 */}
<Switch>
<Route exact path="/" component={Home}></Route>
<Route path="/about" component={About}></Route>
<Route path="/detail" component={Detail}></Route>
</Switch>
</Router>
</div>
);
}
}
export default App;
3、路由跳转和get传值
Link跳转
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>
);
}
}
点击跳转
<Button onClick={this.handleToggle}>detail</Button>
handleToggle=()=>{
this.props.history.push(`/detail?id=${this.state.id}`)
}
4、query-string解析get传值
Detail.js
this.props.location.search
安装依赖 yarn add query-string
import queryString from 'query-string'
class Detail extends Component {
...
componentDidMount() {
var url = this.props.location.search;
var ids = queryString.parse(url); //这里拿到的id值是一个对象 还要再去解析
var id = ids.id;
}
}
export default Detail;