溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

React中如何實(shí)現(xiàn)路由傳參

發(fā)布時(shí)間:2022-03-04 14:25:45 來(lái)源:億速云 閱讀:438 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)React中如何實(shí)現(xiàn)路由傳參,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

react組件通信的其中一種方式--路由傳參(react組件通信的方式有多種,如props、事件回調(diào)、context、router、redux、緩存等等)?,F(xiàn)在單頁(yè)面SPA應(yīng)用的比較廣泛,在不刷新整個(gè)頁(yè)面進(jìn)行部分頁(yè)面的跳轉(zhuǎn),使用路由跳轉(zhuǎn)便在所難免,那么react路由除了進(jìn)行頁(yè)面之間的跳轉(zhuǎn),還有很大一個(gè)作用就是進(jìn)行頁(yè)面或者組件切換時(shí)傳遞參數(shù),從而達(dá)到通信的目的。

  咱們用簡(jiǎn)單的實(shí)例對(duì)react路由跳轉(zhuǎn)傳參的方式進(jìn)行說(shuō)明(本文重點(diǎn)為路由傳參方式,路由配置以及相關(guān)屬性暫不展開(kāi))

  準(zhǔn)備工作,安裝路由依賴:

npm install -S react-router-dom

  之后在頁(yè)面中引入路由:

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

ManageSystem.js里面的某一部分需要路由切換顯示內(nèi)容,Route為需要切換的組件,path為路由路徑,exact為精確匹配,Link為鏈接,to表示跳轉(zhuǎn)的路由路徑,與Route中的path對(duì)應(yīng),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';
//動(dòng)態(tài)加載組件,加快首屏渲染
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,作用是將一個(gè)組件包裹進(jìn)Route里面,
然后react-router的三個(gè)對(duì)象history、location、match就會(huì)被放進(jìn)這個(gè)組件的props屬性中。
*/
export default withRouter(Home)

 重點(diǎn)來(lái)了?。?!

 在切換路由時(shí),傳參方式主要有3種:path動(dòng)態(tài)路徑、query、state 

 首先,path動(dòng)態(tài)路徑法,設(shè)置path的時(shí)候在地址中拼接一個(gè)動(dòng)態(tài)參數(shù),下面的動(dòng)態(tài)參數(shù)為:id

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

在進(jìn)行頁(yè)面切換或跳轉(zhuǎn)時(shí),將所要傳遞的信息拼在地址后面,如:

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

當(dāng)切換到Users時(shí),可以通過(guò)match來(lái)獲取其傳過(guò)來(lái)的信息,Users.js如下

import React from "react";
class Users extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      id: this.props.match.params.id  //此處獲取通過(guò)path動(dòng)態(tài)參數(shù)拼接傳過(guò)來(lái)的信息
    }
  }
  componentDidMount(){
    console.log(this.props,'users props')
  }
  render() {
    return (
      <div>
        <span>我是users:{this.state.id}</span>
      </div>
    )
  }
}
export default Users

獲?。?strong>this.props.match.params.id

可以打印props,查看里面的內(nèi)容,不難發(fā)現(xiàn),props中存在該信息

React中如何實(shí)現(xiàn)路由傳參

 那么對(duì)應(yīng)的編程式跳轉(zhuǎn)為:

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

第二種傳參方法為query,通過(guò)參數(shù)query將信息傳遞過(guò)去

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

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

同樣,打印出來(lái)看看

React中如何實(shí)現(xiàn)路由傳參

 對(duì)應(yīng)的編程式跳轉(zhuǎn)為:

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

第三種傳參方法為state,通過(guò)參數(shù)state將信息傳遞過(guò)去,用法與query一致

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

獲?。?strong>this.props.location.state.text

同樣,打印出來(lái)看看

React中如何實(shí)現(xiàn)路由傳參

 對(duì)應(yīng)的編程式跳轉(zhuǎn)為:

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

ps:query跟state用一個(gè)重要的區(qū)別,那就是在頁(yè)面跳轉(zhuǎn)之后,重新刷新當(dāng)前頁(yè)面,query會(huì)消失,而state不會(huì)消失,即依然保存在location中。

不妨測(cè)試一下,對(duì)Users.js頁(yè)面進(jìn)行修改,如果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

通過(guò)跳轉(zhuǎn),獲取數(shù)據(jù)正常,query存在

React中如何實(shí)現(xiàn)路由傳參

React中如何實(shí)現(xiàn)路由傳參

 重新刷新當(dāng)前頁(yè)面,則query消失

React中如何實(shí)現(xiàn)路由傳參

 頁(yè)面顯示為

React中如何實(shí)現(xiàn)路由傳參

 同樣的過(guò)程使用state傳參方式,location中state刷新當(dāng)前頁(yè)面也不會(huì)消失,推薦state方式。

關(guān)于“React中如何實(shí)現(xiàn)路由傳參”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI