我想使用React JS从URL中获取id,以便从API中加载数据。
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())
我可以通过split()得到这个id,但是它看起来很脏,对吧?有没有一种干净的方法或者原生的方法来达到这个目的呢?我还想知道,也许这不是获取id并将其传递给API的正确方式,对吗?也许会有安全问题,如果有人输入/View/22/22/33/44/ it get 44而不是22
我是个新手,有没有本机或正确的方法来获取页面id,并将其传递给API?
发布于 2020-02-12 18:50:07
使用this.props.match.params.id
const id = this.props.match.params.id;
console.log(id)在路由器中:
<Route exact path='/View/:id' component={View}></Route>发布于 2020-02-12 18:01:36
你可能想要做的是使用像react-router这样的东西,定义路由并获取组件内部的参数。
发布于 2020-02-12 18:11:09
如果你正在为你的应用取消react-router,你可以用useParams()钩子获取你的url参数。
检查下面的链接。https://reacttraining.com/react-router/web/example/url-params
https://stackoverflow.com/questions/60185581
复制相似问题