react-router-dom版本:
"react-router-dom": "5.2.1"
{/* params传参 */} <NavLink to='/layout/First/zhangsan/18'>First</NavLink> <Route path='/layout/First/:name/:age' component={First}></Route> // 获取参数---match this.props.match.params // { // "name": "zhangsan", // "age": "18" // }
- 地址栏显示参数
- 需要配置动态路由
{/* search传参 */} <NavLink to='/layout/Second?name=zhangsan&age=18'>Second</NavLink> <Route path='/layout/Second' component={Second}></Route> // 获取参数---location this.props.location.search // ?name=zhangsan&age=18
地址栏显示参数
{/* state传参 */} <NavLink to={{ pathname: '/layout/Third', state: { name: 'zhangsan', age: 18 } }} > Third </NavLink> <Route path='/layout/Third' component={Third}></Route> // 获取参数---location this.props.location.state // { // "name": "zhangsan", // "age": 18 // }
地址栏不显示参数
{/* params传参 */} <button onClick={this.goToFourth}>buttonFourth</button> // 跳转方法 goToFourth = () => { this.props.history.push('/layout/Fourth/zhangsan/18') } <Route path='/layout/Fourth/:name/:age' component={Fourth}></Route> // 获取参数---match this.props.match.params // { // "name": "zhangsan", // "age": "18" // }
- 地址栏显示参数
- 需要配置动态路由
{/* search传参 */} <button onClick={this.goToFifth}>buttonFifth</button> // 跳转方法 goToFifth = () => { this.props.history.push('/layout/Fifth?name=zhangsan&age=18') } <Route path='/layout/Fifth' component={Fifth}></Route> // 获取参数---location this.props.location.search // ?name=zhangsan&age=18
地址栏显示参数
{/* state传参 */} <button onClick={this.goToSixth}>buttonSixth</button> // 跳转方法 goToSixth = () => { this.props.history.push('/layout/Sixth', { name: 'zhangsan', age: 18 }) } <Route path='/layout/Sixth' component={Sixth}></Route> // 获取参数---location this.props.location.state // { // "name": "zhangsan", // "age": 18 // }
地址栏不显示参数
{/* query传参 */} <button onClick={this.goToSeventh}>buttonSeventh</button> // 跳转方法 goToSeventh = () => { this.props.history.push({ pathname: '/layout/Seventh', query: { name: 'zhangsan', age: 18 } }) } <Route path='/layout/Seventh' component={Seventh}></Route> // 获取参数---location this.props.location.query // { // "name": "zhangsan", // "age": 18 // }
- 地址栏不显示参数
- 刷新获取不到数据
// this.props.location.search getSearch = (searchStr) => { const search = {} const arr = searchStr.slice(1).split('&') arr.forEach((e) => { const item = e.split('=') search[item[0]] = item[1] }) return search }