我只想发出 Ajax 请求以从 REACT.JS 中的 API 获取数据,但是每个 API 都需要(id),我想从浏览器中的 URL 获取该 id,我该怎么做?这是我的代码:
componentDidMount(){
fetch("http://localhost:8000/personal/1")
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
information: json,
})
})
我用 Laravel 制作了 API,上面的代码一切都很好,但正如我所说,我想从浏览器中的 url 获取 id,而不仅仅是像现在这样写,谢谢 :) }
原文由 Osama Mohammed 发布,翻译遵循 CC BY-SA 4.0 许可协议
方法#1
您可以使用来自
react-router-dom
的history
道具,这里有一个详细说明如何操作的链接,https://tylermcginnis.com/react-router-programmatically-navigate/
方法#2
如果你想让它变得超级简单,那么使用
window.location
对象怎么样?假设您在带有 url 的页面上
http://localhost:8000/personal/1
window.location.href
会给http://localhost:8000/personal/1
window.location.pathname
会给出/personal/1
获得
pathname
或href
,您可以使用常规字符串函数,如split(...)
并获取 ID。