简体   繁体   中英

What is the proper way to pass parameters between urls using react router?

With React Router v5.1's additions of useParams, useHistory, and useLocation, along with changing coding conventions brought with react-hooks and functional components, it's gotten confusing trying to figure out the intended way to use a contemporary version of react-router.

When programming navigation with react router, how does one properly pass parameters between different urls?

For example, say I have a component, called component_a , that calls the following when clicked:

history.push("/home"); //history is defined as the return value of useHistory() from react-router-dom

What is the proper way for me to pass some of component_a 's properties to another component called component_b ? Component_b is rendered like so:

<Route path="/home" component={component_b}/>


I'm aware that history.push() takes a second parameter [state] . However I didn't see any examples of it in the docs. I also couldn't find a description of it.

I'm also aware of useParams(), however what if there are too many variables to pass through the url itself?

hooks are there so you don't have to use HOC withRouter anymore to get what you need from router.

trough URL you should only pass data that natively belongs to URL (eg. route name, ID, search params, etc)

with state you can pass whatever you want in theory but in practice you'll probably pass some smaller chunks of data (eg. flags, ID)

with router v5 there's also a new way of constructing the Route

<Route path="/home">
  <YourComponent prop1 prop2 />
</Route>

and there you define all of your component props

for everything else you should use app store like Redux, MobX or Context that you'll update before your history.push("/home"); and access it once you're in <YourComponent />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM