programing

React를 사용하여 현재 전체 URL을 읽으시겠습니까?

madecode 2023. 3. 14. 22:03
반응형

React를 사용하여 현재 전체 URL을 읽으시겠습니까?

React 내에서 전체 URL을 가져오려면 어떻게 해야 합니까?JS 컴포넌트?

는 이런 으로 해야 this.props.location 그것은 .undefined

window.location.href네가 찾고 있는 거야

URL의 전체 경로가 필요한 경우 vanilla Javascript를 사용할 수 있습니다.

window.location.href

패스(도메인명 제외)만을 취득하려면 , 다음의 순서를 사용합니다.

window.location.pathname

console.log(window.location.pathname); //yields: "/js" (where snippets run)
console.log(window.location.href);     //yields: "https://stacksnippets.net/js"

출처 : Location pathname 속성 - W3Schools

아직 "react-router"를 사용하지 않은 경우 다음을 사용하여 설치할 수 있습니다.

yarn add react-router

리액트(Respect."경로" 내의 컴포넌트는 다음 번호로 문의할 수 있습니다.

this.props.location.pathname

도메인 이름을 포함하지 않고 경로를 반환합니다.

@abdulla-zulqarnain 감사합니다!

window.location.href그게 네게 필요한 거야또한 리액트 라우터를 사용하는 경우 useLocationuseHistory 훅을 체크하는 데 도움이 될 수 있습니다.둘 다 읽을 수 있는 경로 이름 속성을 가진 개체를 만들고 다른 작업에 유용합니다.여기 리액트 라우터 훅에 대해 설명하는 유튜브 영상이 있습니다

둘 다 필요한 것을 제공합니다(도메인 이름 없음).

import { useHistory ,useLocation } from 'react-router-dom';
const location = useLocation()
location.pathname

const history = useHistory()
history.location.pathname

this.props.location 는 리액트 컨버전스 기능입니다.사용하려면 를 설치해야 합니다.

참고: 전체 URL을 반환하지 않습니다.

undefined리액트 라우터 외부에 컴포넌트가 있을 수 있기 때문입니다.

해야 합니다.this.props.location에 들어있어요.<Route />다음과 같이 합니다.

<Route path="/dashboard" component={Dashboard} />

컴포넌트 에서 Dashboard에 할 수 .this.props.location

플레인 JS:

window.location.href // Returns full path, with domain name
window.location.origin // returns window domain url Ex : "https://stackoverflow.com"
window.location.pathname // returns relative path, without domain name

리액트 라우터 사용

this.props.location.pathname // returns relative path, without domain name

리액트 후크 사용

const location = useLocation(); // React Hook
console.log(location.pathname); // returns relative path, without domain name

이 페이지에 문서를 조금 더 추가해서 말씀드리자면, 저는 한동안 이 문제에 대해 고민해 왔습니다.

와 같이 쉬운 은 URL을 입니다.window.location.href.

런 음 그 다 리 닐 는 바 해 url 추 출 다 할 를 부 니 습 일 we 수 스 extract can있통let urlElements = window.location.href.split('/')

우리는 그 리 we would then는우?console.log(urlElements)URL에서 생성된 요소를 보려면 URL에 의해 생성된 요소를 참조하십시오.URL에서 .split()을 호출하여 생성된 요소의 배열을 확인합니다.

배열에서 액세스할 인덱스를 찾으면 이 인덱스를 변수에 할당할 수 있습니다.

let urlElelement = (urlElements[0])

이제 URL의 특정 부분이 되는urlElement 값을 원하는 장소에서 사용할 수 있습니다.

현재 라우터 인스턴스 또는 현재 위치를 가져오려면 다음 명령어를 사용하여 상위 컴포넌트를 작성해야 합니다.withRouter부에서react-router-dom. . otherwise, when you are trying to access . 그 이외의 경우는, 에 액세스 하려고 할 때,this.props.location그것은 돌아올 것이다.undefined

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';

class className extends Component {

      render(){
           return(
                ....
                  )
              }
}

export default withRouter(className)

이걸 읽어봐 난 해결책을 찾았어React / NextJs왜냐하면 우리가 직접 사용한다면window.location.href리액션 또는 nextjs에서는 다음과 같은 오류를 발생시킵니다.

Server Error Reference Error: 창이 정의되지 않았습니다.

import React, { useState, useEffect } from "react";
const Product = ({ product }) => {
 const [pageURL, setPageURL] = useState(0);
  useEffect(() => {
    setPageURL(window.location.href);
  })
  return (
     <div>
       <h3>{pageURL}</h3>
      </div>
  );
};

주의: https://medium.com/frontend-digest/why-is-window-not-defined-in-nextjs-44daf7b4604e #:~:text=NextJS%20is%20a%20framework%20, 즉 %20not%20run%20in%20NodeJS입니다.

다른 사람이 언급했듯이, 먼저 당신이 필요로 하는 것은react-router패키지.그렇지만location이 오브젝트에 구문 분석된 URL이 포함되어 있습니다.

그러나 글로벌 변수에 액세스하지 않고 전체 URL을 간절히 원한다면, 가장 빠른 방법은

...

const getA = memoize(() => document.createElement('a'));
const getCleanA = () => Object.assign(getA(), { href: '' });

const MyComponent = ({ location }) => {
  const { href } = Object.assign(getCleanA(), location);

  ...

href완전한 URL이 포함되어 있습니다.

위해서memoize나는 주로 사용한다.lodash대부분의 경우 필요 없이 새로운 요소를 생성하지 않기 위해 구현됩니다.

추신: 물론 당신이 시도하고 싶은 오래된 브라우저의 제약을 받지 않는다는 것입니다.new URL()하지만 기본적으로 전체 상황은 거의 무의미합니다. 왜냐하면 어떤 방법으로든 글로벌 변수에 접근하기 때문입니다.그럼 왜 사용하지 않는가?window.location.href대신?

언급URL : https://stackoverflow.com/questions/39823681/read-the-current-full-url-with-react

반응형