React组件通信之路由传参(react-router-dom)

2022-04-15 0 993
目录

      最近在学习react,现在的工作中使用的是vue,在学习的过程中对两者进行比较,加深理解。

      以下是react中的一小部分知识点,我个人觉得也是比较常用的知识点,react组件通信的其中一种方式–路由传参(react组件通信的方式有多种,如props、事件回调、context、router、redux、缓存等等)。现在单页面SPA应用的比较广泛,在不刷新整个页面进行部分页面的跳转,使用路由跳转便在所难免,那么react路由除了进行页面之间的跳转,还有很大一个作用就是进行页面或者组件切换时传递参数,从而达到通信的目的。

      咱们用简单的实例对react路由跳转传参的方式进行说明(本文重点为路由传参方式,路由配置以及相关属性暂不展开)

      准备工作,安装路由依赖:

    npm install -S react-router-dom
    

      之后在页面中引入路由:

    import Home from './component/ManageSystem';
    import { BrowserRouter as Router } from 'react-router-dom'
    function App() {
      return (
        <Router>               //路由包裹,首页面里面的一个或多个页面可能需要路由切换
          <div id="App">
            <Home />
          </div>
        </Router>
      );
    }
     
    export default App

    ManageSystem.js里面的某一部分需要路由切换显示内容,Route为需要切换的组件,path为路由路径,exact为精确匹配,Link为链接,to表示跳转的路由路径,与Route中的path对应,Redirect为重定向。

    import React from 'react';
    import Loadable from '../utils/loadable'
    import {Route,Link,withRouter,Redirect,Switch} from "react-router-dom";
    import { Button } from 'element-react';
    //动态加载组件,加快首屏渲染
    const About = Loadable(() => import('./About.js'))
    const Users = Loadable(() => import('./Users.js'))
    class Home extends React.Component {
        render() {
    	    return (
    		<div style={{ position: 'relative' }}>
    		    <nav style={{ position: 'absolute', top: '0', left: '60%' }}>
    				<ul>
    				    <li style={{ marginBottom: '10px' }}>
    				        <Link to={{pathname:"/home/about",query:{ text: '666' }}}>About</Link>
    				    </li>
    			        <li>
    			            <Link to={{pathname:"/home/users/999",state:{ text: '888' }}}>Users</Link>
    					</li>
    				</ul>
    			</nav>
    			<div style={{ position: 'absolute', top: '20px', right: '20px' }}>
    			    <Switch>
    				    <Route exact path="/home" component={() => { return null }}>
    				    </Route>
    				    <Route exact path="/home/about" component={About}>
    				    </Route>
    				    <Route exact path="/home/users/:id" component={Users}>
    				    </Route>
    				    <Redirect exact from="/" to='/home' />
    			    </Switch>
    			</div>
    		</div>
    		);
    	}
    }
    /*
    高阶组件中的withRouter,作用是将一个组件包裹进Route里面,
    然后react-router的三个对象history、location、match就会被放进这个组件的props属性中。
    */
    export default withRouter(Home)

     重点来了!!!

     在切换路由时,传参方式主要有3种:path动态路径、query、state 

     首先,path动态路径法,设置path的时候在地址中拼接一个动态参数,下面的动态参数为:id

    <Route exact path="/home/users/:id" component={Users}>
    </Route>

    在进行页面切换或跳转时,将所要传递的信息拼在地址后面,如:

    <Link to={{pathname:"/home/users/999"}}>Users</Link>

    当切换到Users时,可以通过match来获取其传过来的信息,Users.js如下

    import React from "react";
    class Users extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          id: this.props.match.params.id  //此处获取通过path动态参数拼接传过来的信息
        }
      }
      componentDidMount(){
        console.log(this.props,'users props')
      }
      render() {
        return (
          <div>
            <span>我是users:{this.state.id}</span>
          </div>
        )
      }
    }
    export default Users

    获取:this.props.match.params.id

    可以打印props,查看里面的内容,不难发现,props中存在该信息

    React组件通信之路由传参(react-router-dom)

     那么对应的编程式跳转为:

    <button onClick={() => { this.props.history.push({ pathname: '/home/users/999' }) }}>about</button>
     
    //同样,用this.props.match.params.id进行取值

    第二种传参方法为query,通过参数query将信息传递过去

    <Link to={{pathname:"/home/users",query:{ text: '666' }}}>Users</Link>

    获取:this.props.location.query.text

    同样,打印出来看看

    React组件通信之路由传参(react-router-dom)

     对应的编程式跳转为:

    <button onClick={() => { this.props.history.push({ pathname: '/home/users/999', query: { text: '666' } }) }}>Users</button>
     
    //同样,获取方式this.props.location.query.text

    第三种传参方法为state,通过参数state将信息传递过去,用法与query一致

    <Link to={{pathname:"/home/users",state:{ text: '666' }}}>Users</Link>

    获取:this.props.location.state.text

    同样,打印出来看看

    React组件通信之路由传参(react-router-dom)

     对应的编程式跳转为:

    <button onClick={() => { this.props.history.push({ pathname: '/home/users/999', state: { text: '666' } }) }}>Users</button>
     
    //同样,获取方式this.props.location.state.text

    ps:query跟state用一个重要的区别,那就是在页面跳转之后,重新刷新当前页面,query会消失,而state不会消失,即依然保存在location中。

    不妨测试一下,对Users.js页面进行修改,如果query不存在,显示“query已消失”

    import React from "react";
    class Users extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          text: this.props.location.query ? this.props.location.query.text : 'query已消失'
        }
      }
      componentDidMount(){
        console.log(this.props,'users props')
      }
      render() {
        return (
          <div>
            <span>我是users:{this.state.text}</span>
          </div>
        )
      }
    }
    export default Users

    通过跳转,获取数据正常,query存在

    React组件通信之路由传参(react-router-dom)

    React组件通信之路由传参(react-router-dom)

     重新刷新当前页面,则query消失

    React组件通信之路由传参(react-router-dom)

     页面显示为

    React组件通信之路由传参(react-router-dom)

     同样的过程使用state传参方式,location中state刷新当前页面也不会消失,推荐state方式。

    总结:本文主要讲述react路由跳转传参的3种方式,在项目中涉及到某个页面跳转需要将某些信息传递给跳转目的页面,不妨考虑这几种方式。区别:动态地址方式虽然简单,但是传参的方式单一,只能拼在地址,且为字符串,当传递的信息过长时,地址看起来比较乱,信息也会暴露出来;而对于query来说,传参方式虽与state一致,但是有一点,跳转之后刷新当前页,query会消失,而state不会。

    对比Vue中路由传参方式:

    Vue组件间的通信方式(多种场景,通俗易懂,建议收藏)

    到此这篇关于React组件通信之路由传参(react-router-dom)的文章就介绍到这了,更多相关React 路由传参内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!

    免责声明:
    1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

    2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
    如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
    如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

    NICE源码网 JavaScript React组件通信之路由传参(react-router-dom) https://www.niceym.com/18748.html