一、React路由傳參的三種方式
React Router提供了3種方式來傳遞參數:params、query、state。下面我們將介紹每種方式的使用方法和優缺點。
1. Params傳參
Params是一種通過URL片段來傳遞數據的方式。在Route組件中可以通過路徑參數定義,例如:
{
/*在App.js定義路由*/
<Route path="/article/:id" component={Article} />
}
在Link組件中可以通過to屬性來傳遞參數:
{
<Link to=`/article/${article.id}`>查看詳情</Link>
}
在被鏈接組件中可以通過props.match.params獲取參數:
{
class Article extends React.Component {
render() {
const { match } = this.props;
const id = match.params.id; //獲取參數
return <div>Article ID: {id}</div>;
}
}
}
優點:可以定義動態路由,傳遞的參數可以直接在props中獲取。
缺點:對於大型應用程序,可能需要多個地方獲取該參數,因此不太方便。
2. Query傳參
Query是一種通過URL參數來傳遞數據的方式。在Link組件中可以通過to屬性傳遞參數:
{
<Link to={{pathname: '/article', search: '?id=' + article.id}}>查看詳情</Link>
}
在被鏈接組件中可以通過props.location.search獲取參數:
{
class Article extends React.Component {
render() {
const { location } = this.props;
const searchParams = new URLSearchParams(location.search); //獲取參數
const id = searchParams.get('id');
return <div>Article ID: {id}</div>;
}
}
}
優點:將參數集中在URL上,方便管理。
缺點:URL太長,不太美觀;參數只能是字符串,如果需要傳遞對象需要進行序列化和反序列化。
3. State傳參
State通過Link組件中的state屬性傳遞參數。例如:
{
<Link to={{
pathname: '/article',
state: { id: article.id }
}}>查看詳情</Link>
}
在被鏈接組件中可以通過props.location.state獲取參數:
{
class Article extends React.Component {
render() {
const { location } = this.props;
const id = location.state.id; //獲取參數
return <div>Article ID: {id}</div>;
}
}
}
優點:參數不會被暴露在URL中,安全性較高。
缺點:如果用戶使用了瀏覽器的前進或後退按鈕,參數會丟失。因此不太適合需要永久保存參數狀態的情況。
二、React路由傳參數
使用React Router中的參數傳遞,可以方便地將參數傳遞給組件,在組件中進行處理。下面是一個例子。
{
/*在App.js定義路由*/
<Route path="/article/:id" component={Article} />
/*在Link組件中傳遞參數*/
<Link to=`/article/${article.id}`>查看詳情</Link>
/*在被鏈接組件中獲取參數*/
class Article extends React.Component {
render() {
const { match } = this.props;
const id = match.params.id;
//渲染頁面
return (
<div>
<h1>{this.props.title}</h1>
<p>{this.props.content}</p>
</div>
);
}
}
}
上面的例子中,參數id被傳遞到了Article組件中,在組件中可以根據傳遞的參數進行頁面渲染。
三、React路由傳參丟失
在使用React路由傳參時,有時會出現參數丟失的情況。下面我們來分析一下可能的原因和解決方法。
1. 刷新頁面導致參數丟失
在使用params方式傳遞參數時,參數是作為URL的一部分存在的。如果用戶在刷新頁面時,URL會改變,從而導致參數丟失。
解決方法:使用localStorage或sessionStorage將參數保存在本地,這樣用戶刷新頁面時可以從本地存儲中重新獲取參數。
2. 瀏覽器前進或後退按鈕導致參數丟失
在使用state方式傳遞參數時,如果用戶使用了瀏覽器的前進或後退按鈕,參數會丟失。
解決方法:將參數保存在URL中或使用localStorage或sessionStorage。
3. 組件傳遞給子組件時參數丟失
在父組件中使用Route組件傳遞參數給子組件時,如果不使用render函數,則無法傳遞參數。
解決方法:使用render函數進行組件渲染,並將參數傳遞給組件。
四、React路由組件
React Router提供了一些內置的組件,可以方便地構建應用程序的路由。下面是一些常用的路由組件。
1. Route組件
Route組件是React Router中最基本的組件,可以用來定義路由和渲染組件。下面是一個例子。
{
<Route path="/article/:id" component={Article} />
//...
class Article extends React.Component {
render() {
//渲染頁面
return (
<div>
<h1>{this.props.title}</h1>
<p>{this.props.content}</p>
</div>
);
}
}
}
上面的例子中,Route組件定義了路徑為”/article/:id”的路由,並將Article組件與該路由對應。當用戶訪問該路由時,React Router會自動渲染Article組件,並將URL參數傳遞給該組件。
2. Switch組件
Switch組件用於對路由進行分組,只渲染第一個匹配的路由。例如:
{
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/about" component={About} />
<Route path="/article/:id" component={Article} />
<Route component={NotFound} />
</Switch>
}
上面的例子中,Switch組件將”/”、”/about”、”/article/:id”和默認路由包括在一起,並且只有第一個匹配的路由會被渲染,可以有效防止默認路由重複渲染的問題。
3. withRouter組件
withRouter組件是React Router提供的一個高階組件(HOC),用於將路由對象注入到組件中。使用withRouter將允許你在不是路由組件的任何地方使用路由對象。
{
import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
handleClick() {
this.props.history.push('/about');
}
render() {
return (
<div onClick={() => this.handleClick()}>
Go to About
</div>
);
}
}
export default withRouter(MyComponent);
}
上面的例子中,使用withRouter將路由對象注入到MyComponent中,在組件中就可以使用history.push方法進行路由跳轉。
五、React路由重定向
React Router提供了Redirect組件,用於實現路由重定向。例如,當用戶未登錄時,可以將其重定向到登錄頁面。
{
import { Redirect } from 'react-router-dom';
class MyComponent extends React.Component {
render() {
const isLoggedIn = false;
return isLoggedIn ? (
<div>You are logged in.</div>
) : (
<Redirect to="/login" />
);
}
}
}
上面的例子中,如果用戶未登錄,則React Router將其重定向到”/login”頁面。
六、React路由面試題
下面是一些React路由面試題,可以幫助你加深對React路由的理解。
1. 路由是否可以傳遞函數作為參數?
答案:不能。因為React Router路由組件只能接受React組件作為參數。
2. 如何在React Router中實現動態路由?
答案:使用params方式傳遞參數。在Route組件的path屬性中使用冒號(:)定義參數,例如”/article/:id”。在Link組件中使用to屬性傳遞參數,例如:<Link to=`/article/${article.id}`>查看詳情</Link>。在被鏈接組件中可以通過props.match.params獲取參數。
3. 如何實現路由跳轉?
答案:使用history對象中的push或replace方法進行路由跳轉。例如:this.props.history.push(‘/about’)。
七、React路由參數配置
React Router使用組件來配置路由。Route組件需要兩個屬性,path和component。其中,path表示路徑,component表示要渲染的組件。下面是一個例子。
{
import { Route } from 'react-router-dom';
class MyComponent extends React.Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
</div>
);
}
}
<Route path="/hello" component={MyComponent} />
}
上面的例子中,當用戶訪問”/hello”頁面時,MyComponent組件將會被渲染。
八、React路由式導航如何傳值
使用React Router可以方便地實現式導航。例如,將導航欄作為組件,在點擊時根據路由進行頁面跳轉。下面是一個例子。
{
import { NavLink } from 'react-router-dom';
class Nav extends React.Component {
render() {
return (
<div>
<ul>
<li><NavLink to="/home" activeClassName="active">Home</NavLink></li>
<li><NavLink to="/about" activeClassName="active">About</NavLink></li>
<li><NavLink to="/contact" activeClassName="active">Contact</NavLink></li>
</ul>
</div>
);
}
}
}
上面的例子中,使用NavLink組件實現導航欄。當用戶點擊鏈接時,React Router根據路由進行頁面跳轉,並使用activeClassName屬性添加樣式。
總結
React路由傳參
原創文章,作者:JSAUK,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/317786.html