详解React路由传参方法汇总记录
React中传参方式有很多,通过路由传参的方式也是必不可少的一种。
本文记录项目中会用到的路由传参方式: 路由跳转传参API + 目标路由获取参数的方式。
一、动态路由
跳转方法
Link
<Link to={{ pathname: "/user/add/1" }}>跳转新增页面</Link>
history.push
this.props.history.push("/user/add/1");
获参方法
this.props.match.params
二、路由query显示参数
Link跳转
<Link to={{ pathname: "/user/add", query: { id: 1 } }}> 跳转新增页面 </Link>
history.push
this.props.history.push({ pathname: "/user/add", //参数 query: { id: 1 }, });
获参方法
this.props.location.query
三、路由state隐式参数
Link跳转
<Link to={{ pathname: "/user/add", state: { id: 1 } }}> 跳转新增页面 </Link>
history.push
this.props.history.push({ pathname: "/user/add", state: { id: 1 }, });
获参方法
this.props.location.state
代码DEMO
入口App组件
class App extends React.Component { render() { return ( <BrowserRouter> <Route path="/user" exact component={User} /> //动态路由 <Route path="/user/add/:id?" component={UserAdd} /> {/* <Redirect to="/user" /> */} </BrowserRouter> ); } }
动态路由Demo
User组件
import React, { Component } from "react"; import { Link } from "react-router-dom"; export default class User extends Component { render() { return ( <div> <div className="user">User</div> {/* <Link to={{ pathname: "/user/add/1" }}>跳转新增页面</Link> */} <button onClick={() => { // 1. // this.props.history.push("/user/add/1"); // 2. this.props.history.push({ pathname: "/user/add/1", }); }} > 跳转新增页面 </button> </div> ); } }
UserAdd组件
import React, { Component } from "react"; export default class UserAdd extends Component { render() { console.log("this.props.match.params:", this.props.match.params); return <div>UserAdd</div>; } }
路由query显示参数Demo
User组件
import React, { Component } from "react"; import { Link } from "react-router-dom"; export default class User extends Component { render() { return ( <div> <div className="user">User</div> <Link to={{ pathname: "/user/add", query: { id: 1 } }}> 跳转新增页面 </Link> <button onClick={() => { this.props.history.push({ pathname: "/user/add", query: { id: 1 }, }); }} > 跳转新增页面 </button> </div> ); } }
路由state隐式参数Demo
User组件
import React, { Component } from "react"; import { Link } from "react-router-dom"; export default class User extends Component { render() { return ( <div> <div className="user">User</div> <Link to={{ pathname: "/user/add", state: { id: 1 } }}> 跳转新增页面 </Link> <button onClick={() => { this.props.history.push({ pathname: "/user/add", state: { id: 1 }, }); }} > 跳转新增页面 </button> </div> ); } }
到此这篇关于详解React路由传参方法汇总记录的文章就介绍到这了,更多相关React路由传参内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)