IT박스

반응 라우터 v4에서 history.push / Link / Redirect로 매개 변수를 전달하는 방법은 무엇입니까?

itboxs 2020. 6. 27. 11:49
반응형

반응 라우터 v4에서 history.push / Link / Redirect로 매개 변수를 전달하는 방법은 무엇입니까?


this.props.history.push('/page')React-Router v4에서 매개 변수를 어떻게 전달할 수 있습니까?

.then(response => {
       var r = this;
        if (response.status >= 200 && response.status < 300) {
             r.props.history.push('/template');
          });

우선, 당신이 할 필요가 없다 var r = this;이에서 같이 if statement콜백 자체의 컨텍스트를 참조하는 구성 요소 컨텍스트를 반응 참조하는 당신은 화살표 기능을 사용하고 있기 때문이다.

문서에 따르면 :

history 객체에는 일반적으로 다음과 같은 속성과 메서드가 있습니다.

  • length-(숫자) 히스토리 스택의 항목 수
  • action-(문자열) 현재 조치 (PUSH, REPLACE 또는 POP)
  • location-(객체) 현재 위치. 다음과 같은 속성이있을 수 있습니다.

    • pathname-(문자열) URL의 경로
    • search-(문자열) URL 쿼리 문자열
    • 해시-(문자열) URL 해시 조각
    • state-이 위치가 스택으로 푸시 될 때 푸시 (경로, 상태)에 제공된 (문자열) 위치 별 상태. 브라우저 및 메모리 기록에서만 사용할 수 있습니다.
  • push (path, [state])-(function) 새 항목을 기록 스택에 넣습니다.
  • replace (path, [state])-(function) 기록 스택의 현재 항목을 교체합니다
  • go (n)-(함수) 사용 내역 스택에서 n 개의 항목만큼 포인터를 이동합니다.
  • goBack ()-(함수) go (-1)와 동일
  • goForward ()-(함수) go (1)와 같습니다.
  • 차단 (프롬프트)-(기능) 탐색 방지

따라서 탐색하는 동안 소품을 기록 개체에 전달할 수 있습니다.

this.props.history.push({
  pathname: '/template',
  search: '?query=abc',
  state: { detail: response.data }
})

또는 유사위한 Link구성 요소 또는 Redirect구성 요소

<Link to={{
      pathname: '/template',
      search: '?query=abc',
      state: { detail: response.data }
    }}> My Link </Link>

/templateroute 로 렌더링 된 컴포넌트에서 전달 된 prop에 접근 할 수 있습니다.

this.props.location.state.detail

소품에서 히스토리 또는 위치 객체를 사용할 때는 구성 요소를로 연결해야합니다 withRouter.

문서에 따라 :

라우터

고차 컴포넌트 <Route>'s를 통해 히스토리 오브젝트의 특성 및 가장 근접한 항목에 액세스 할 수 있습니다 withRouter. withRouterrender와 같은 props로 경로가 변경 될 때마다 컴포넌트를 다시 <Route>렌더링 props: { match, location, history }합니다.


당신이 사용할 수있는,

this.props.history.push("/template", { ...response }) 또는 this.props.history.push("/template", { response: response })

/template다음 코드를 통해 구성 요소 에서 구문 분석 된 데이터에 액세스 할 수 있습니다.

const state = this.props.location.state

API 문서에 대한 링크는 다음과 같습니다.


URL 매개 변수를 전달해야하는 경우

자신의 사이트에 프로그래머 타일러 McGinnis의 뛰어난 포스트 설명을 포스트 링크

다음은 코드 예제입니다.

  1. history.push 구성 요소에서 :

    this.props.history.push(/home:${this.state.userID})

  2. 라우터 구성 요소에서 경로를 정의합니다.

    <Route path='/home:myKey' component={Home} />

  3. 홈 컴포넌트에서 :

    componentDidMount(){ const { myKey } = this.props.match.params console.log(myKey ) }


It is not necessary to use withRouter. This works for me:

In your parent page,

<BrowserRouter>
   <Switch>
        <Route path="/routeA" render={(props)=> (
          <ComponentA {...props} propDummy={50} />
        )} />

        <Route path="/routeB" render={(props)=> (
          <ComponentB {...props} propWhatever={100} />
          )} /> 
      </Switch>
</BrowserRouter>

Then in ComponentA or ComponentB you can access

this.props.history

object, including the this.props.history.push method.


Add on info to get query parameters.

const queryParams = new URLSearchParams(this.props.location.search);
console.log('assuming query param is id', queryParams.get('id');

For more info about URLSearchParams check this link URLSearchParams

참고URL : https://stackoverflow.com/questions/44121069/how-to-pass-params-with-history-push-link-redirect-in-react-router-v4

반응형