簡體   English   中英

如何在反應中從 URL 中正確提取參數

[英]How to properly extract params from a URL in react

我創建了一個網頁來顯示個人資料。 默認情況下,配置文件頁面會加載用戶信息,但如果我使用關聯的用戶 ID 調用配置文件頁面,我也可以加載來自其他用戶的信息。

URL 是/profile或者可以是/profile?id=12334

在我的代碼中,我只是在單擊按鈕時在 URL 中添加了 ID:

<a href="/profile?id=123123">

我的個人資料頁面現在只是呈現假數據,但我不知道如何提取 id 並檢查id是否存在且不為空。


import React from 'react';
import './Profile.css';

import UserProfile from '../assets/fake/studentinfo'
import TextContents from '../assets/translations/TextContents';
import Gallery from 'react-grid-gallery';
import DetailReview from '../components/materialdesign/DetailReview';
import {Tabs, Tab}  from 'react-bootstrap';
import EmptyTile from '../components/EmptyTile';


class Profiles extends React.Component{

    constructor(props, context) {
        super(props);
        this.state = {isUserAccount: true, userId: '', userInfo: UserProfile.User1.values};
    }

    componentDidMount() {
        let { id } = useParams();
        if((id!==null) && (id !== '')) {
            this.setState({userId: id})
            this.setState({isUserAccount: false})
            this.fetchData(id);
        }
    }

    fetchData = id => {
        this.setState({userInfo: UserProfile.User2.values})
    };


    render(){
        

        const IMAGES =
        [{
                src: "https://c2.staticflickr.com/9/8817/28973449265_07e3aa5d2e_b.jpg",
                thumbnail: "https://c2.staticflickr.com/9/8817/28973449265_07e3aa5d2e_n.jpg",
                thumbnailWidth: 156,
                thumbnailHeight: 156
        },
        {
                src: "https://c2.staticflickr.com/9/8356/28897120681_3b2c0f43e0_b.jpg",
                thumbnail: "https://c2.staticflickr.com/9/8356/28897120681_3b2c0f43e0_n.jpg",
                thumbnailWidth: 156,
                thumbnailHeight: 156
        },
        
        {
                src: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_b.jpg",
                thumbnail: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_n.jpg",
                thumbnailWidth: 156,
                thumbnailHeight: 156
        },
        {
            src: "https://c2.staticflickr.com/9/8356/28897120681_3b2c0f43e0_b.jpg",
            thumbnail: "https://c2.staticflickr.com/9/8356/28897120681_3b2c0f43e0_n.jpg",
            thumbnailWidth: 156,
            thumbnailHeight: 156
        }]

        return(
            <div className="profile-container">
                <div className="profile-header" 
                    style={{ backgroundImage: `url(${UserProfile.User1.values.profileHeaderImag})`}}>
                        <img 
                        src={UserProfile.User1.values.profileImg} 
                        alt="profileImg"
                        className="profile-header-image-user"/>                    
                </div>
                <div className="profile-content">
                    <h1> {UserProfile.User1.values.name} </h1>
                    <h3> {UserProfile.User1.values.city}  </h3>
                    <h2> {TextContents.Biography} </h2>
                    <p> {UserProfile.User1.values.bio}  </p>
                    <h2> {TextContents.PhotosVideos} </h2>
                    <div className="profile-gallery">
                        <Gallery id="ReactGridGallery" images={IMAGES}/>
                    </div>
                </div>
                <div className="profile-tabs">
                    <Tabs defaultActiveKey="profile" id="uncontrolled-tab-example">
                        <Tab eventKey="yourclasses" title="Your Classes">
                            <div>
                            <EmptyTile text={TextContents.CreateYourOwnClass} url="/createaclass"/>
                            </div>
                        </Tab>
                        <Tab eventKey="joinedclasses" title="Joined Classes">
                        <div>
                            <EmptyTile text={TextContents.DiscoverANewExp} url="/createaclass"/>
                        </div>
                        </Tab>
                        <Tab eventKey="bookmarks" title="Bookmarks">
                        <p> {TextContents.NoBookMarkYet} </p>
                        </Tab>
                        <Tab eventKey="yourhosting" title="Your Hosting">
                        <div>
                            <EmptyTile text={TextContents.HaveBusinessOrHome} url="/createahost"/>
                        </div>
                        </Tab>
                    </Tabs>
                </div>
                <div className="profile-content">
                    <h2>{TextContents.Reviews}</h2>
                        {
                            UserProfile.User1.values.reviews.map((review_item, i) => {
                                return (<DetailReview data={review_item} />);
                            })
                        }
                </div>
            </div>
        )
    }   
}

export default Profiles;

稍后數據將被正確的替換,但現在,我只想確保我可以輕松地從 URL 中提取 id

謝謝

如果你使用react-router-dom你可以使用他們的一些鈎子來解構 url 的東西。

在這種情況下,您正在尋找的鈎子是useParams

const { id } = useParams();

如果您使用的是 class 組件; 您可以使用高階組件withRouter ,或者如果您有提前匹配的路徑,則可以使用matchPath

URLURLSearchParams是你所追求的,它不需要 React,它是原生 JS。 link.searchParams.get('id')就足夠了,但這取決於您的目標瀏覽器,因此您可能需要在代碼中添加polyfill ,否則:

const {searchParams} = new URL(a.href);
if (searchParams.has('id')) {
  // do your thing with ...
  console.log(searchParams.get('id'));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM