programing

쿼리 문자열에서 매개 변수 값을 가져오려면 어떻게 해야 합니까?

starjava 2023. 3. 18. 08:12
반응형

쿼리 문자열에서 매개 변수 값을 가져오려면 어떻게 해야 합니까?

에서 routes.jsx 파일을 요?__firebase_request_key싱글 사인온 URL

http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla

루트했는데, 'Da'가:redirectParam는, 전술한파라메타를 않습니다.

<Router>
  <Route path="/" component={Main}>
    <Route path="signin" component={SignIn}>
      <Route path=":redirectParam" component={TwitterSsoButton} />
    </Route>
  </Route>
</Router>

리액트 라우터 v6, 후크 사용

react-router-dom v6에는 useSearchParams라는 새로운 후크가 있습니다.그래서...

const [searchParams, setSearchParams] = useSearchParams();
searchParams.get("__firebase_request_key")

얻을 수 있다"blablabla" Objectetc.searchParams의 URLearchParams를

리액트 라우터 v4/v5, 훅 없음, 범용

Router Respect Router v4를 만 할 수 .this.props.location.search(또는 useLocation, 아래 참조).이유는 nbeuchat의 답변을 참조하십시오.

예: qs 라이브러리를 Import한 경우qs 수 있다

qs.parse(this.props.location.search, { ignoreQueryPrefix: true }).__firebase_request_key

다른 라이브러리는 query-string 입니다.검색 문자열 해석에 대한 자세한 내용은 이 답변을 참조하십시오.IE 호환성이 필요 없는 경우는, 을 사용할 수도 있습니다.

new URLSearchParams(this.props.location.search).get("__firebase_request_key")

하는 컴포넌트에 는, 「」를 합니다.this.props.locationuse Location을 사용합니다.참고:window.location.search변경 시 리액트 렌더링을 트리거할 수 없습니다.가 ('비기능')의 Switch라우터가 제공하는 소품 중 하나에 액세스하려면 라우터와 함께 사용해야 합니다.

리액트 라우터 v3

리액트 라우터는 이미 위치를 해석하여 Route Component에 소품으로 전달합니다.query 부분(url의 ? 이후)에는, 다음의 순서로 액세스 할 수 있습니다.

this.props.location.query.__firebase_request_key

라우터 내부에서 콜론(:)으로 구분된 경로파라미터 값을 찾고 있는 경우 이들 값은 경유로 액세스 할 수 있습니다.

this.props.match.params.redirectParam

이것은 최신 리액트라우터 v3 버전에 적용됩니다(어느 버전인지 불명).에서는 「」를 사용하고 있는 되고 있습니다.this.props.params.redirectParam.

일반

하기 위한 nizam.sp의 제안

console.log(this.props)

어떤 경우에도 도움이 될 것입니다.

리액트 라우터 v4

「」를 사용합니다.component

<Route path="/users/:id" component={UserPage}/> 
this.props.match.params.id

구성요소는 루트 소품과 함께 자동으로 렌더링됩니다.


「」를 사용합니다.render

<Route path="/users/:id" render={(props) => <UserPage {...props} />}/> 
this.props.match.params.id

루트 소품이 렌더링 함수로 전달됩니다.

리액트 라우터 v3

Router 에서는 React Router v3에서을 얻을 수 .this.props.location.search (?qs1=naisarg&qs2=parma)를 들어, 「」를 ,let params = queryString.parse(this.props.location.search)는 , , 을 줄 것입니다.{ qs1 : 'naisarg', qs2 : 'parmar'}

리액트 라우터 v4

v4의 "v4"는this.props.location.query는 더 이상 존재하지 않습니다.대신 를 사용하여 쿼리 파라미터를 직접 해석하거나 등의 기존 패키지를 사용하여 해석해야 합니다.

으로 리액트 라우터 및 리액트라우터 v4를 사용한 의 예를 .query-string★★★★★★★★★★★★★★★★★★.

import { withRouter } from 'react-router-dom';
import queryString from 'query-string';
    
class ActivateAccount extends Component{
    someFunction(){
        let params = queryString.parse(this.props.location.search)
        ...
    }
    ...
}
export default withRouter(ActivateAccount);

합리적인

라우터의 은 「」를 입니다.query을 사용하다

쿼리 문자열 구문 분석/문자열을 약간 다르게 수행하는 많은 일반적인 패키지가 있으며, 이러한 차이는 일부 사용자에게는 "올바른" 방법이고 다른 사용자에게는 "잘못된" 방법일 수 있습니다.만약 리액트 라우터가 "올바른" 것을 선택했다면, 그것은 일부 사람들에게만 옳을 것이다.그런 다음 다른 사용자가 선호하는 쿼리 구문 분석 패키지를 대체할 방법을 추가해야 합니다.키-값 쌍을 구문 분석할 필요가 있는 React Router의 검색 문자열은 내부적으로 사용되지 않으므로 "올바른" 검색 문자열을 선택할 필요가 없습니다.

[...]

4.0에서는 모든 '배터리 포함' 기능을 삭제하고 기본적인 라우팅으로 돌아가는 접근방식을 취하고 있습니다.쿼리 문자열 구문 분석, 비동기 로드 또는 Redux 통합 또는 기타 매우 구체적인 것이 필요한 경우 해당 사용 사례에 맞게 라이브러리에 추가할 수 있습니다.불필요한 번거로움이 적고, 고객의 취향이나 요구에 맞추어 커스터마이즈 할 수 있습니다.

GitHub에서 자세한 내용을 보실 수 있습니다.

제가 알기로는 그것을 할 수 있는 방법은 세 가지가 있습니다.

1. 정규식을 사용하여 쿼리 문자열을 가져옵니다.

2. 브라우저 API를 사용할 수 있습니다.image 현재 URL은 다음과 같습니다.

http://www.google.com.au?token=123

우리는 단지 123을 받고 싶다.

첫번째

 const query = new URLSearchParams(this.props.location.search);

그리고나서

const token = query.get('token')
console.log(token)//123
  1. 세 번째 라이브러리인 '스트링'을 사용합니다.최초 설치

    npm i query-string 그런 다음 현재 javascript 파일로 가져옵니다.

    query-string'에서 queryString 가져오기

다음 단계에서는 현재 URL에서 'token'을 가져옵니다.다음 절차를 수행합니다.

const value=queryString.parse(this.props.location.search);
const token=value.token;
console.log('token',token)//123

2019년 2월 25일 갱신

4. 현재 URL이 다음과 같은 경우:

http://www.google.com.au?app=home&act=article&aid=160990

파라미터를 취득하는 함수를 정의합니다.

function getQueryVariable(variable)
{
        var query = window.location.search.substring(1);
        console.log(query)//"app=article&act=news_content&aid=160990"
        var vars = query.split("&");
        console.log(vars) //[ 'app=article', 'act=news_content', 'aid=160990' ]
        for (var i=0;i<vars.length;i++) {
                    var pair = vars[i].split("=");
                    console.log(pair)//[ 'app', 'article' ][ 'act', 'news_content' ][ 'aid', '160990' ] 
        if(pair[0] == variable){return pair[1];}
         }
         return(false);
}

다음을 통해 '원조'를 받을 수 있습니다.

getQueryVariable('aid') //160990

에는 React Router v4가 . props.location.query object(기트허브 설명 참조).따라서 새로운 프로젝트에서는 인정된 답변이 적용되지 않습니다.

v4의 솔루션은 외부 라이브러리 쿼리 문자열을 사용하여props.location.search

const qs = require('query-string');
//or
import * as qs from 'query-string';

console.log(location.search);
//=> '?foo=bar'

const parsed = qs.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}

할 수.this.props.location하려면 , 를 사용합니다window★★★★★★ 。

const search = window.location.search;
const params = new URLSearchParams(search);
const foo = params.get('bar');

리액트 라우터 5.1+

5.1에서는 다양한 훅이 도입되었으며, 이는 여기에서 유용하게 사용될 수 있습니다.

예:

<Route path="/test/:slug" component={Dashboard} />

그럼 우리가 방문했다면

http://localhost:3000/test/signin?_k=v9ifuf&__firebase_request_key=blablabla

다음과 같이 검색할 수 있습니다.

import { useLocation } from 'react-router';
import queryString from 'query-string';

const Dashboard: React.FC = React.memo((props) => {
    const location = useLocation();

    console.log(queryString.parse(location.search));

    // {__firebase_request_key: "blablabla", _k: "v9ifuf"}

    ...

    return <p>Example</p>;
}

이 원라이너에서는 플레인 JavaScript를 사용하여 React Hook과 React Class Component 모두에서 사용할 수 있습니다.

https://www.hunterisgod.com/ ? city = leipzigleipzig

let city = (new URLSearchParams(window.location.search)).get("city")

리액트 라우터 v4

const urlParams = new URLSearchParams(this.props.location.search)
const key = urlParams.get('__firebase_request_key')

현재 시험 중이니 참고하시기 바랍니다.

브라우저 호환성은 https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams#Browser_compatibility 에서 확인하십시오.

http://localhost:8000/#/signin?id=12345

import React from "react";
import { useLocation } from "react-router-dom";

const MyComponent = () => {
  const search = useLocation().search;
const id=new URLSearchParams(search).get("id");
console.log(id);//12345
}

, 는 이 리액션이 합니다.one-line function이 될 수 : ) could could could could 。 : )

const getQueryParams = (query = null) => [...(new URLSearchParams(query||window.location.search||"")).entries()].reduce((a,[k,v])=>(a[k]=v,a),{});

또는 다음과 같습니다.

const getQueryParams = (query = null) => (query||window.location.search.replace('?','')).split('&').map(e=>e.split('=').map(decodeURIComponent)).reduce((r,[k,v])=>(r[k]=v,r),{});

또는 풀 버전:

const getQueryParams = (query = null) => {
  return (
    (query || window.location.search.replace("?", ""))

      // get array of KeyValue pairs
      .split("&") 

      // Decode values
      .map((pair) => {
        let [key, val] = pair.split("=");

        return [key, decodeURIComponent(val || "")];
      })

      // array to object
      .reduce((result, [key, val]) => {
        result[key] = val;
        return result;
      }, {})
  );
};

§:
URL:...?a=1&b=c&d=test
★★★★★★★★★★★★★★

getQueryParams()
//=> {a: "1", b: "c", d: "test"}

getQueryParams('type=user&name=Jack&age=22')
//=> {type: "user", name: "Jack", age: "22" }

react-parames를 간단하게 체크할 수 있습니다.라우터에서 정의한 한 코드를 사용하여 쿼리 파라미터를 취득할 수 있습니다.

this.props.params.userId

리액트 라우터 돔 V6 https://reactrouter.com/docs/en/v6/hooks/use-search-params

import * as React from "react";
import { useSearchParams } from "react-router-dom";

function App() {
  let [searchParams, setSearchParams] = useSearchParams();

  function handleSubmit(event) {
    event.preventDefault();
    // The serialize function here would be responsible for
    // creating an object of { key: value } pairs from the
    // fields in the form that make up the query.
    let params = serializeFormQuery(event.target);
    setSearchParams(params);
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>{/* ... */}</form>
    </div>
  );
}

리액트 라우터 돔 V5까지

function useQueryParams() {
    const params = new URLSearchParams(
      window ? window.location.search : {}
    );

    return new Proxy(params, {
        get(target, prop) {
            return target.get(prop)
        },
    });
}

리액트 훅은 훌륭합니다.

이 URL과 같은 /users?page=2&count=10&fields=name,email,phone

// app.domain.com/users?page=2&count=10&fields=name,email,phone

const { page, fields, count, ...unknown } = useQueryParams();

console.log({ page, fields, count })
console.log({ unknown })

space가 포함되어 "hyphone("-")" space("")와 같이 수 .{ page, fields, count, ...unknown }

당신은 다음과 같은 잠정적인 임무를 수행할 필요가 있을 것입니다.

// app.domain.com/users?utm-source=stackOverFlow

const params = useQueryParams();

console.log(params['utm-source']);

라우터가 이와 같은 경우

<Route exact path="/category/:id" component={ProductList}/>

이 ID는 이렇게 됩니다.

this.props.match.params.id

다음과 같은 URL이 있다고 합니다.

http://localhost:3000/callback?code=6c3c9b39-de2f-3bf4-a542-3e77a64d3341

그 URL에서 코드를 추출하고 싶은 경우는, 이하의 방법이 도움이 됩니다.

const authResult = new URLSearchParams(window.location.search); 
const code = authResult.get('code')

서드파티제 라이브러리나 복잡한 솔루션 없이 모든 것을 한 줄로 처리할 수 있습니다.방법은 다음과 같습니다

let myVariable = new URLSearchParams(history.location.search).get('business');

당신이 바꿀 필요가 있는 것은 오직 당신만의 파라메타 이름을 가진 '비즈니스' 단어만 바꾸면 됩니다.

예: url.com?business=안녕하세요

myVariable의 결과는 hello가 됩니다.

나는 이 문제를 해결하는 데 애를 먹었다.위의 어느 것도 동작하지 않는 경우는, 이것을 대신 사용해 주세요.create-react-app을 사용하고 있다.

요구 사항들

react-flash-dom": "^4.3.1"

솔루션

라우터가 지정된 위치

<Route path="some/path" ..../>

다음과 같이 전달할 매개 변수 이름을 추가합니다.

<Route path="some/path/:id" .../>

일부/경로를 렌더링하는 페이지에서 이 값을 지정하여 다음과 같이 파라미터 이름 콜 ID를 표시할 수 있습니다.

componentDidMount(){
  console.log(this.props);
  console.log(this.props.match.params.id);
}

기본값을 내보내는 마지막 부분

export default withRouter(Component);

Import를 포함해야 합니다.

import { withRouter } from 'react-router-dom'

console.log(this.props)를 사용하면 전달된 내용을 확인할 수 있습니다.재미있게 보내!

React Router v5.1에서 도입된 후크:

위해서

<Route path="/posts/:id">
  <BlogPost />
</Route>

후크를 사용하여 매개 변수/ID에 액세스할 수 있습니다.

const { id } = useParams();

여기 더 있어요.

맞으면 안 맞히지 this.props 답변에 예상하셨던 경우, 다음을 해야 할 수.★★★★★★★★★★★★★★★★★★★★★★★★★·withRouter(v4) :

import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>You are now at {location.pathname}</div>
    )
  }
}

// Create a new component that is "connected" (to borrow redux terminology) to the router.  
const TwitterSsoButton = withRouter(ShowTheLocation)  

// This gets around shouldComponentUpdate
withRouter(connect(...)(MyComponent))

// This does not
connect(...)(withRouter(MyComponent))

사실 서드파티 라이브러리를 사용할 필요가 없습니다.순수 자바스크립트로 만들 수 있습니다.

다음 URL을 고려합니다.

https://example.com?yourParamName=yourParamValue

이것으로, 이하를 알 수:

const url = new URL(window.location.href);
const yourParamName = url.searchParams.get('yourParamName');

요컨대

const yourParamName = new URL(window.location.href).searchParams.get('yourParamName')

다른 스마트 솔루션(권장)

const params = new URLSearchParams(window.location.search);
const yourParamName = params.get('yourParamName');

요컨대

const yourParamName = new URLSearchParams(window.location.search).get('yourParamName')

주의:

다중 값을 가진 매개 변수에 대해 "get" 대신 "getAll"을 사용합니다.

https://example.com?yourParamName [ ] = yourParamValue 1 & yourParamName [ ] = yourParamValue 2

const yourParamName = new URLSearchParams(window.location.search).getAll('yourParamName[]')

결과는 다음과 같습니다.

["yourParamValue1", "yourParamValue2"]

시험해 보다

http://localhost:4000/#/amoos?id=101

// ReactJS
import React from "react";
import { useLocation } from "react-router-dom";

const MyComponent = () => {
    const search = useLocation().search;
    const id = new URLSearchParams(search).get("id");
    console.log(id); //101
}



// VanillaJS
const id = window.location.search.split("=")[1];
console.log(id); //101

React routerv4에서 v4 로 는 상 능 공 습 하 no니 from v gives the4않다 longer제4 you onwards v이기이이더지후을 no v from4 gives longerquery params directly in its 바로 그 안에location물건.건 - 왜? - 상부 지시요

쿼리 문자열 구문 분석/문자열을 약간 다르게 수행하는 많은 일반적인 패키지가 있으며, 이러한 차이는 일부 사용자에게는 "올바른" 방법이고 다른 사용자에게는 "잘못된" 방법일 수 있습니다.만약 리액트 라우터가 "올바른" 것을 선택했다면, 그것은 일부 사람들에게만 옳을 것이다.그런 다음 다른 사용자가 선호하는 쿼리 구문 분석 패키지를 대체할 방법을 추가해야 합니다.키-값 쌍을 구문 분석할 필요가 있는 React Router의 검색 문자열은 내부적으로 사용되지 않으므로 "올바른" 검색 문자열을 선택할 필요가 없습니다.

그것을 포함하면, 위치 분석만 하는 것이 더 이치에 맞을 것입니다.쿼리 개체를 기대하는 보기 구성 요소를 검색합니다.

You can do this generically by overriding the 이 작업은 일반적인 방법으로 수행할 수 있습니다.withRouter부에서react-router like맘에 들다

custom With Router.js

import { compose, withPropsOnChange } from 'recompose';
import { withRouter } from 'react-router';
import queryString from 'query-string';

const propsWithQuery = withPropsOnChange(
    ['location', 'match'],
    ({ location, match }) => {
        return {
            location: {
                ...location,
                query: queryString.parse(location.search)
            },
            match
        };
    }
);

export default compose(withRouter, propsWithQuery)

리액트 라우터 v6

출처: 리액트라우터에서의 쿼리 문자열(검색 파라미터) 취득

것을 사용하다useSearchParams과 훅.get()★★★★

const Users = () => {
  const [searchParams] = useSearchParams();
  console.log(searchParams.get('sort')); // 'name'

  return <div>Users</div>;
};

이 방법을 사용하면 하나 또는 몇 개의 매개 변수를 읽을 수 있습니다.

보너스 객체로 매개 변수 가져오기:

스트링 가 있는 는, 「」를 할 수 .Object.fromEntries음음음같 뭇매하다

const Users = () => {
  const [searchParams] = useSearchParams();
  console.log(Object.fromEntries([...searchParams])); // ▶ { sort: 'name', order: 'asecnding' }
  return <div>Users</div>;
};

자세한 내용과 라이브 데모 보기:리액트 라우터에서의 쿼리 문자열(검색 파라미터) 취득

다음 리액트 훅을 사용할 수 있습니다.

  1. URL이 변경될 경우 후크 상태 업데이트
  2. SSRtypeof window === "undefined"만 하면 됩니다.window에러를 발생시킵니다(실행해 보겠습니다.
  3. Proxy숨겨져 있기 에 실행이 숨겨져 있습니다.undefined됩니다.null

검색 파라미터를 오브젝트로 취득하는 함수는 다음과 같습니다.

const getSearchParams = <T extends object>(): Partial<T> => {
    // server side rendering
    if (typeof window === "undefined") {
        return {}
    }

    const params = new URLSearchParams(window.location.search) 

    return new Proxy(params, {
        get(target, prop, receiver) {
            return target.get(prop as string) || undefined
        },
    }) as T
}

그리고 이렇게 후크로 사용합니다.

const useSearchParams = <T extends object = any>(): Partial<T> => {
    const [searchParams, setSearchParams] = useState(getSearchParams())

    useEffect(() => {
        setSearchParams(getSearchParams())
    }, [typeof window === "undefined" ? "once" : window.location.search])

    return searchParams
}

URL 이 다음과 같은 경우:

/app?page=2&count=10

이렇게 읽을 수 있습니다.

const { page, count } = useQueryParams();

console.log(page, count)

this.props.params.your_param_name과가있있 있있있다다

이렇게 하면 쿼리 문자열에서 매개 변수를 가져올 수 있습니다.
해 주세요.console.log(this.props);★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

componentDidMount(){
    //http://localhost:3000/service/anas
    //<Route path="/service/:serviceName" component={Service} />
    const {params} =this.props.match;
    this.setState({ 
        title: params.serviceName ,
        content: data.Content
    })
}

조금 늦었을 수도 있지만, 이 리액트 훅은 URL 쿼리에서 값을 가져오거나 설정하는 데 도움이 됩니다.https://github.com/rudyhuynh/use-url-search-params (제가 작성).

할 수 .react-router고객님의 경우의 코드 샘플은 다음과 같습니다.

import React from "react";
import { useUrlSearchParams } from "use-url-search-params";

const MyComponent = () => {
  const [params, setParams] = useUrlSearchParams()
  return (
    <div>
      __firebase_request_key: {params.__firebase_request_key}
    </div>
  )
}

현재 위치에서 검색 매개 변수를 추출하기 위한 간단한 후크를 만들 수 있습니다.

import React from 'react';
import { useLocation } from 'react-router-dom';

export function useSearchParams<ParamNames extends string[]>(...parameterNames: ParamNames): Record<ParamNames[number], string | null> {
    const { search } = useLocation();
    return React.useMemo(() => { // recalculate only when 'search' or arguments changed
        const searchParams = new URLSearchParams(search);
        return parameterNames.reduce((accumulator, parameterName: ParamNames[number]) => {
            accumulator[ parameterName ] = searchParams.get(parameterName);
            return accumulator;
        }, {} as Record<ParamNames[number], string | null>);
    }, [ search, parameterNames.join(',') ]); // join for sake of reducing array of strings to simple, comparable string
}

기능 컴포넌트 내에서 다음과 같이 사용할 수 있습니다.

// current url: http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla
const { __firebase_request_key } = useSearchParams('__firebase_request_key');
// current url: http://localhost:3000/home?b=value
const searchParams = useSearchParameters('a', 'b'); // {a: null, b: 'value'}

누군가가 그 이유를 명확하게 설명해 줄 수 있을지도 모릅니다만, App.js 페이지에 있는 Create React App의 신규 인스톨로부터 위치를 찾기 위해서 소품을 찾으려 하고 있는 경우는, 다음과 같이 됩니다.

TypeError: 정의되지 않은 속성 '검색'을 읽을 수 없습니다.

App.js를 홈루트로 사용하고 있는데

<Route exact path='/' render={props => (

App.js에서만 window.location을 사용하여 사용할 수 있었습니다.

import queryString from 'query-string';
...
const queryStringParams = queryString.parse(window.location.search);

사용할 수 있는 파라미터에 액세스해야 하는 컴포넌트

this.props.location.state.from.search

이 표시됩니다( 나타남).?sign부호)를 참조해 주세요.

언급URL : https://stackoverflow.com/questions/35352638/how-to-get-parameter-value-from-query-string

반응형