reactjs 从react.js中的url获取ID

7tofc5zh  于 2023-01-30  发布在  React
关注(0)|答案(9)|浏览(186)

我只想发出 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,
    })
})

我做的API由Laravel,和每件事的工作与上面的代码很好,但正如我所说的,我想从浏览器中的URL的ID不只是写它现在,谢谢你:)}

rfbsl7qr

rfbsl7qr1#

在React Hooks中,您应该使用useParams().ex-这是您的url -http://localhost:8000/personal/1
因此,在本例中,使用const { id } = useParams()
现在,如果你执行console.log(id),它会给予你url的确切id,在这个例子中,它会给你1。
useParams()从url中提取id并让我们使用它。

wmtdaxz3

wmtdaxz32#

    • 方法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
一旦有了pathnamehref,就可以使用常规的字符串函数(如split(...))来获取ID。

yfwxisqw

yfwxisqw3#

在Route中,您可以指定一个参数,然后使用useParams获取该参数。

// App.js
<Route path='/post/:id' component={PostDetail} />

// Single post component
import axios from "axios";    
import { useState, useEffect } from "react"
import { useParams } from "react-router-dom";

// Get ID from URL
const params = useParams();
    
    const [posts, setPosts] = useState([])
    
        useEffect(()=> {
            axios.get(`http://localhost:5000/posts/${params.id}`)
            .then(res => {
                console.log(res)
                setPosts(res.data)
            })
            .catch(err =>{
                console.log(err)
            })
        }, [params.id])

从这里开始,您可以在组件中使用{post.yourdata}。

pu3pd22g

pu3pd22g4#

对于挂钩用户

import React from "react";
import {useParams} from 'react-router-dom';

const ProductDetails = () => {
const {id} = useParams();
  return (
    <>
      <h1>Product id: {id}</h1>
    </>
  );
};

export default ProductDetails;
nbysray5

nbysray55#

例如,在类组件中,可以通过添加constructor访问ID,然后从props访问ID

export class PostDetail extends React.Component {
  
  constructor(props) {
    super(props);
    console.log(this.props.match.params.id)
    this.state = {
      data: [],
      loaded: false,
      placeholder: "Loading"
    };
  }

  render(){
    return(<h1>Post Detail</h1>);
  }
}
vwoqyblh

vwoqyblh6#

如果你在前端使用react,最好使用rect-router,这样你就可以很容易地操作路径参数,并使用match.params.[paramName]在你的组件中访问它们。
通过使用普通的js,你可以使用window.location对象。

  • http://localhost:8000/personal/1 => window.location.pathname = personal/1 [路径参数]
  • http://localhost:8000/personal?id=1 => window.location.search = ?id=1 [搜索参数]

如果你使用搜索参数,有一个很好的库query-string来解析它们,当然,如果你使用路径名,你需要手动去除你的参数。

goqiplq2

goqiplq27#

记住useParams来自react路由器dom而不是react数据包

import { useParams } from 'react-router-dom'
iszxjhcz

iszxjhcz8#

首先,在app.js或navigation.js等导航文件中添加此路线

<Route path="/home/:id"  element={<Landing />} />

而不是在登录屏幕或页面上使用此代码获取该值

const params = useParams()
  console.log(params)
moiiocjp

moiiocjp9#

如果你在React中使用类组件,你可以使用(this.props.match.params.id),这将从url中获取id。

相关问题