Get the App
SLTechnology News&Howtos  ›  Development  › 

How to pass parameters to react router

Shulou Source: shulou.com Published: 2022-05-31 20:08:46 10月03日 Update

This article mainly introduces the relevant knowledge of "how to transfer parameters from react router". The editor shows you the operation process through actual cases. The operation method is simple, fast and practical. I hope this article "how to transfer parameters from react router" can help you solve the problem.

React router parameter transfer methods: 1, the use of wildcards to pass parameters, can only pass strings, parameters will not be lost when refreshing the page; 2, use query to pass parameters, but refresh the page will lead to the loss of parameters; 3, the use of state parameters, you can pass objects, arrays, etc., once the refresh page parameters will be lost.

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

How to transfer parameters to react router

There are three ways to pass parameters in react router routing: passing parameters through wildcards, query and state.

1. Pass parameters by wildcard

How Route is defined:

Link components:

Wildcard character

Parameter acquisition:

This.props.match.params.name

Advantages: simple and fast, and when refreshing the page, the parameters will not be lost.

Cons: only strings can be passed, and if too many values are passed, the url will become long and ugly.

If you want to pass an object, you can use JSON.stringify () to convert it to a string, and then use JSON.parse () to turn it back after another page receives it.

2 、 query

How Route is defined:

Link components:

Var query = {undefined pathname:'/ query', query:'I passed the value through query'} query

Parameter acquisition:

This.props.location.query

Advantages: elegant, transferable object

Disadvantages: refresh the page, missing parameters

3 、 state

How Route is defined:

State

Link components:

Var state = {undefined pathname:'/ state', state:'I passed the value through state'}

Parameter acquisition:

This.props.location.state

The this.props.location.state here ='I passed the value through query'

Advantages: elegant, transferable object

Disadvantages: refresh the page, missing parameters

This is the end of the introduction to "how to transmit react router parameters". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Tags: Parameters pages objects methods wildcards advantages characters strings knowledge components disadvantages elegance methods industry transmissible different practical ugly content practical Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Shulou Technology NVidia vpn Apple