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
4 Answers
Reset to default 4Use 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
版权声明:本文标题:javascript - Reactjs get URL pathname id - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742134187a2422296.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论