[reactjs] 반응-쿼리 문자열에서 매개 변수 값을 얻는 방법

__firebase_request_key서버에서 경로 재 지정한 후 Twitter의 싱글 사인온 프로세스에서 생성 된 URL에서 매개 변수 값 을 캡처하기 위해 route.jsx 파일에서 경로를 정의하려면 어떻게 해야합니까?

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

나는 다음과 같은 경로 구성으로 시도했지만 :redirectParam언급 된 매개 변수를 잡지 않습니다.

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



답변

라우터 v3 반응

React Router는 이미 위치를 구문 분석하고이를 RouteComponent 에 소품으로 전달합니다 . 다음을 통해 (URL에서? 뒤에) 쿼리에 액세스 할 수 있습니다

this.props.location.query.__firebase_request_key

라우터 내부에서 콜론 (:)으로 구분 된 경로 매개 변수 값을 찾으려면이를 통해 액세스 할 수 있습니다.

this.props.match.params.redirectParam

이는 최신 React Router v3 버전에 적용됩니다 (확실하지 않음). 이전 라우터 버전은 사용하는 것으로보고되었습니다 this.props.params.redirectParam.

React Router v4 및 React Router v5, 일반

React Router v4는 더 이상 쿼리를 구문 분석하지 않지만을 통해서만 액세스 할 수 있습니다 this.props.location.search. 이유는 nbeuchat ‘s answer를 참조하십시오 .

예를 들어 qs 라이브러리를 가져 와서 가져올 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.location 경우 후크 useLocation으로 합니다 . 참고로 사용할 수는 window.location.search있지만 변경 사항에 대한 반응 렌더링을 트리거 할 수는 없습니다. 당신의 (비 기능) 구성 요소는의 직접적인 자식이 아닌 경우 Switch사용해야하는 withRouter를 라우터에서 제공 소품에 액세스은.

일반

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 반응

React Router v3을 사용하면 this.props.location.search(? qs1 = naisarg & qs2 = parmar) 에서 쿼리 문자열을 얻을 수 있습니다 . 예를 let params = queryString.parse(this.props.location.search)들어을 사용하면{ qs1 : 'naisarg', qs2 : 'parmar'}

라우터 v4 반응

React Router v4에서는 this.props.location.query더 이상 존재하지 않습니다. this.props.location.search대신 직접 사용하거나 같은 기존 패키지를 사용하여 쿼리 매개 변수를 구문 분석 해야합니다 query-string.

다음은 React Router 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가 “올바른”것을 선택한 경우 일부 사람들에게만 적합합니다. 그런 다음 다른 사용자가 선호하는 쿼리 구문 분석 패키지를 대체 할 수있는 방법을 추가해야합니다. 키-값 쌍을 구문 분석해야하는 React Router의 검색 문자열은 내부적으로 사용되지 않으므로 이들 중 어느 것이 “올바른”것인지 선택할 필요가 없습니다.

[…]

4.0에 대한 접근 방식은 모든 “포함 된 배터리”종류의 기능을 제거하고 기본 라우팅으로 돌아가는 것입니다. 쿼리 문자열 구문 분석 또는 비동기 로딩 또는 Redux 통합 또는 매우 구체적인 것이 필요한 경우 사용 사례에 맞게 라이브러리를 추가 할 수 있습니다. 덜 까다로워서 필요하지 않으며 특정 환경 설정 및 요구에 맞게 항목을 사용자 정의 할 수 있습니다.

GitHub 에 대한 전체 토론을 찾을 수 있습니다 .


답변

내가 아는 한 세 가지 방법이 있습니다.

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

2. 브라우저 API를 사용할 수 있습니다. 현재 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

3. ‘query-string’이라는 세 번째 라이브러리를 사용하십시오. 먼저 설치

npm i query-string

그런 다음 현재 자바 스크립트 파일로 가져옵니다.

 import queryString from 'query-string'

다음 단계는 현재 URL에서 ‘토큰’을 얻는 것입니다. 다음을 수행하십시오.

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

도움이 되길 바랍니다.

25/02/2019에 업데이트 됨

  1. 현재 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 객체 가 없습니다 ( github 참조) 토론 ). 따라서 수락 된 답변은 최신 프로젝트에는 적용되지 않습니다.

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'}


답변

React 후크를 사용하면에 액세스 할 수 없습니다 this.props.location. URL 매개 변수를 캡처하려면 windowobject를 사용하십시오 .

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


답변

라우터 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