首頁  >  文章  >  web前端  >  react withrouter的用法是什麼

react withrouter的用法是什麼

WBOY
WBOY原創
2022-04-19 11:05:572231瀏覽

react withrouter用來將一個元件包進Route裡面,並將「react-router」的三個history、location、match物件傳入props對象,引入語法為「import{withRouter}from.. .」。

react withrouter的用法是什麼

本教學操作環境:Windows10系統、react17.0.1版、Dell G3電腦。

react withrouter的用法是什麼

withRouter的作用就是, 如果我們某個東西不是一個Router, 但是我們要依靠它去跳轉一個頁面, 比如點擊頁面的logo, 返回首頁, 這時候就可以使用withRouter來做.withRouter,

作用是將一個元件包裹進Route裡面, 然後react-router的三個物件history, location, match就會被放進這個元件的props屬性中.(我的理解加上之後可以寫程式設計時導航,不想vue可以在全域用this.$router.push()來完成)

將react-router 的history、location、match三個物件傳入props物件

預設情況下必須是經過路由匹配渲染的元件才存在this.props,才擁有路由參數,才能使用函數跳轉的寫法,執行this.props.history. push('/detail')跳到對應路由的頁面

然而不是所有元件都直接與路由相連(透過路由跳到此元件)的,當這些元件需要路由參數時,使用withRouter就可以給此元件傳入路由參數,此時就可以使用this.props

如何使用withRouter:

例如app.js這個頁面,不是透過路由跳轉過來的,而是直接從瀏覽器中輸入地址打開的,如果不使用withRouter, 此組件的this.props為空,沒法執行props中的history、location、match等方法, 如: 函數式跳轉this.props.push('/detail')

設定withRouter很簡單只需要兩步:1引入, 2執行, 如下

import React,{Component} from 'react'
import {Switch,Route,NavLink,Redirect,withRouter} from 'react-router-dom' //引入withRouter
import One from './One'
import NotFound from './NotFound'
class App extends Component{
    //此时才能获取this.props,包含(history, match, location)三个对象
    console.log(this.props);  //输出{match: {…}, location: {…}, history: {…}, 等}
    render(){return (<div className=&#39;app&#39;>
            <NavLink to=&#39;/one/users&#39;>HOME</NavLink>
            <NavLink to=&#39;/one/companies&#39;>OTHER</NavLink>
            <Switch>
                <Route path=&#39;/one/:type?&#39; component={One} />
                <Redirect from=&#39;/&#39; to=&#39;/one&#39; exact />
                <Route component={NotFound} />
            </Switch>
        </div>)
    }
}
export default withRouter(App);  //这里要执行一下WithRouter

推薦學習:《react視頻教程

以上是react withrouter的用法是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn