react withrouter is used to wrap a component into Route, and pass the three history, location, and match objects of "react-router" into the props object. The introduction syntax is "import{withRouter}from.. ."
The operating environment of this tutorial: Windows 10 system, react17.0.1 version, Dell G3 computer.
The function of withRouter is that if something is not a Router, but we have to rely on it to jump to a page, such as clicking on the logo of the page, return Home page. At this time, you can use withRouter to do it. withRouter,
functions to wrap a component into Route, and then the three objects history, location, and match of react-router will be put into this component. In the props attribute. (My understanding is that you can write programming navigation later. If you don’t want vue, you can use this.$router.push() globally to complete it)
Change the history, location, and match of react-router Three objects are passed in to the props object
By default, this.props must exist in a component rendered by routing matching, and only then can it have routing parameters, and then function jump writing can be used to execute this.props.history. push('/detail') jumps to the page corresponding to the route
However, not all components are directly connected to the route (jump to this component through the route). When these components require routing parameters, use withRouter You can pass in routing parameters to this component, and you can use this.props
How to use withRouter:
For example, the app.js page is not routed It jumps here, but opens it directly by entering the address in the browser. If withRouter is not used, this.props of this component is empty, and the history, location, match and other methods in the props cannot be executed, such as: Functional jump Turn this.props.push('/detail')
Setting up withRouter is very simple and only requires two steps: 1 introduction, 2 execution, as follows
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='app'> <NavLink to='/one/users'>HOME</NavLink> <NavLink to='/one/companies'>OTHER</NavLink> <Switch> <Route path='/one/:type?' component={One} /> <Redirect from='/' to='/one' exact /> <Route component={NotFound} /> </Switch> </div>) } } export default withRouter(App); //这里要执行一下WithRouter
Recommended learning: "react video Tutorial》
The above is the detailed content of What is the usage of react withrouter. For more information, please follow other related articles on the PHP Chinese website!