Home  >  Article  >  Web Front-end  >  How to pass parameters in react router

How to pass parameters in react router

WBOY
WBOYOriginal
2022-04-21 17:14:444003browse

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.

How to pass parameters in react router

The operating environment of this tutorial: Windows 10 system, react17.0.1 version, Dell G3 computer.

How to pass parameters in react router

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=&#39;/path/:name&#39; 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=&#39;/query&#39; component={Query}/>

Link component:

var query = {undefined
        pathname: &#39;/query&#39;,
        query: &#39;我是通过query传值 &#39;
}
<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: &#39;/state&#39;,
        state: &#39;我是通过state传值&#39;
    }
    <Route path=&#39;/state&#39; 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What is setstate in reactNext article:What is setstate in react