How to pass parameters in react router: 1. Use wildcards to pass parameters. You can only pass strings. The parameters will not be lost when refreshing the page. 2. Use query to pass parameters. You can pass objects, but refreshing the page will Resulting in loss of parameters; 3. Use state to pass parameters. You can pass objects, arrays, etc. Once the page is refreshed, the parameters will be lost.
The operating environment of this tutorial: Windows 10 system, react17.0.1 version, Dell G3 computer.
There are three ways to pass parameters in react router routing: passing parameters through wildcards, query parameters and state parameters.
1. Wildcard parameter passing
Route definition method:
<Route path='/path/:name' component={Path}/>
Link component:
<Link to="/path/通过通配符传参">通配符</Link>
Parameter acquisition:
this.props.match.params.name
Advantages: Simple and fast, and the parameters will not be lost when the page is refreshed.
Disadvantages: Only strings can be passed, and if too many values are passed, the URL will become long and ugly.
If you want to transfer an object, you can use JSON.stringify() to convert it into a string, and then use JSON.parse() to convert it back after receiving it on another page.
2. query
Route definition method:
<Route path='/query' component={Query}/>
Link component:
var query = {undefined pathname: '/query', query: '我是通过query传值 ' }
<Link to={query}>query</Link>
Parameter acquisition:
this.props.location.query
Advantages: Elegant, transferable objects
Disadvantages: Refresh the page, parameters are lost
3, state
Route definition method:
<Link to={state}>state</Link>
Link component:
var state = {undefined pathname: '/state', state: '我是通过state传值' } <Route path='/state' component={State}/>
Parameter acquisition:
this.props.location.state
here this.props.location.state === 'I pass the value through query'
Advantages: elegant, can pass objects
Disadvantages: refresh the page, parameters are lost
Recommended learning: "react video tutorial"
The above is the detailed content of How to pass parameters in react router. For more information, please follow other related articles on the PHP Chinese website!