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>;
 }
}

详解React路由传参方法汇总记录 

路由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>
  );
 }
}

详解React路由传参方法汇总记录 

路由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路由传参方法汇总记录

风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com