admin管理员组

文章数量:1323698

I want to get id from URL to load data from API, using React JS

let url = 'http://localhost:3000/View/22'; //window.location.href originally instead of this
let object = new URL(url);
let path = object.pathname
console.log(path) 
//

console.log(path.split('/').pop())

I want to get id from URL to load data from API, using React JS

let url = 'http://localhost:3000/View/22'; //window.location.href originally instead of this
let object = new URL(url);
let path = object.pathname
console.log(path) 
//

console.log(path.split('/').pop())

I can get this id by split() but it's seems dirty, right? Is there a clean way or native way to get this? Also I am wondering, maybe this is not right way to get id and pass it to API , am I right? maybe there will be security issue, if someone enter /View/22/22/33/44/ it get 44 not 22

I am new to React, is there native way or correct way to get page id, and pass it to API?

Share Improve this question edited Feb 18, 2020 at 12:20 Pedram 16.6k10 gold badges47 silver badges73 bronze badges asked Feb 12, 2020 at 9:56 danny cavanaghdanny cavanagh 1352 silver badges8 bronze badges 5
  • but it's seems dirty, right? Not really, there's nothing wrong with it. You could use regex for it if you really wanted, but that's no better or worse. – Rory McCrossan Commented Feb 12, 2020 at 9:57
  • 2 there will be security issue, if someone enter /View/22/22/33/44/ it get 44 not 22 In this case access the values by index, not always by retrieving the final one – Rory McCrossan Commented Feb 12, 2020 at 9:58
  • are you using react-router for your app? – gnujoow Commented Feb 12, 2020 at 10:00
  • @gnujoow yes I am – danny cavanagh Commented Feb 12, 2020 at 10:05
  • @dannycavanagh You'll always get the first number value in your path object.pathname.match('[0-9]+')[0] – Juhil Somaiya Commented Feb 12, 2020 at 10:06
Add a ment  | 

4 Answers 4

Reset to default 4

Use this.props.match.params.id

const id = this.props.match.params.id;
console.log(id)

In router:

<Route exact path='/View/:id' ponent={View}></Route>

What you probably want to do is use something like react-router, define routes and get the parameters inside a ponent.

if you are unsing react-router for your app, you can get your url parameter with useParams() hook.

check following link. https://reacttraining./react-router/web/example/url-params

Try this:

 let url = 'http://localhost:3000/View/22';
 var id = url.substring(url.lastIndexOf('/') + 1);

本文标签: javascriptReactjs get URL pathname idStack Overflow