programing

프로그래밍 방식으로 탐색할 때 라우터를 반응시키고 데이터를 전달하시겠습니까?

prostudy 2022. 3. 9. 10:37
반응형

프로그래밍 방식으로 탐색할 때 라우터를 반응시키고 데이터를 전달하시겠습니까?

우리는 다음 방법으로 다른 길을 찾을 수 있다.

this.props.router.push('/some/path')

탐색할 때 매개 변수(객체)를 보낼 수 있는 방법이 있는가?

내가 생각할 수 있는 다른 선택사항들이 있지만, 통과가 가능한지 궁금하다.object혹시 가능할까?

  • 나는 오브젝트의 ID를 내장하고 새로운 페이지에서 오브젝트를 서버에서 다시 가져올 수 있다.

  • 아니면 물건을 환원소처럼 글로벌 저장소에 보관할 수도 있다.(이 물체는 곧 매장에서 제거해야 한다.그래서 애당초 거기에 갖다 놓는 것이 좋지 않을 수도 있다고 생각하고 있다)

라우터 사용 반응location물건들의 속성 중 하나location목적어는state.

this.props.router.push({
  pathname: '/other-page',
  state: {
    id: 7,
    color: 'green'
  }
})

탐색서가 있다location루트가 일치하는 구성 요소에 주입되어 다음 작업을 통해 상태에 액세스할 수 있음this.props.location.state.

한 가지 명심해야 할 것은 앞으로 없을 것이라는 점이다.state사용자가 페이지로 직접 이동할 경우, 데이터가 없을 때 데이터를 로드하기 위한 메커니즘이 필요할 수 있다.

현재의 답은 시대에 뒤떨어져 있다.

라우터 6 반응:

사용useNavigate스위치:

const navigate = useNavigate();
navigate('/other-page', { state: { id: 7, color: 'green' } });

그런 다음 '/다른 페이지'의 상태 데이터에 액세스할 수 있다.useLocation스위치:

const {state} = useLocation();
const { id, color } = state; // Read values passed on state

라우터 4 또는 5 응답:

history.push를 호출하여 두 번째 매개 변수로 개체를 전달하십시오.

props.history.push('/other-page', { id: 7, color: 'green' }))

그런 다음 다음을 통해 '/다른 페이지'의 상태 데이터에 액세스할 수 있다.

props.location.state

기능 구성 요소의 경우react-router-dom:^5.2.0개념을 정확하게 만들기 위해 아주 간단한 예를 들어보자.

import { useHistory } from "react-router-dom";

  function Sender(){ 
  
  const history = useHistory();

  const goToReceiver = () => {
    history.push("/receiver", { name:'Mr',age:23 });
  }

  return <button onClick={goToReceiver}>Go To Receiver</button>
  }

이제 어떻게 데이터가 생성되었는지 봅시다.receiver route

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

  function Receiver(){ 
  
  const location = useLocation();

    return <div>
             <p>{location.state.name}</p>
             <p>{location.state.age}</p>
           </div>
  }

리액터-루터-돔의 히스토리 후크를 사용할 수 있다.

아래 코드는 "/대시보드"인 명시된 경로로 데이터를 전달하는 것이다.

let history = useHistory();

history.push({
            pathname: '/dashboard',
            state:{
                tags: 'your-value' 
            }
    });

그리고 "/dashboard"에서 당신은 위의 데이터를 받기 위해 history()를 사용할 수 있다.

아래 코드는 당신이 당신의 데이터를 받는 것이다.

const Dashboard =()=>{

 let {location} = useHistory();

 return (<>{location.state.tags}</>)
}

리액션 라우터에서 프로그래밍 방식으로 탐색할 때 쿼리 매개 변수 전달

history 객체는 history.push 및 history.replace를 모두 사용하여 현재 위치를 프로그래밍 방식으로 변경할 수 있다.

    history.push('/home?the=query', { some: 'state' })

역사물을 소품으로 구성요소로 전달하면.그런 다음, 기록 객체에서 사용할 수 있는 반응 라우터 방법을 사용하여 프로그래밍 방식으로 탐색할 수 있다.

이제 여러분이 '루터'라고 불리는 소품으로 역사 유물을 물려주고 있다고 가정해보자.그래서 그것은 다음과 같은 클래스 기반 구문을 가진 구성요소 내부에서 참조될 것이다.

this.props.router

푸시 또는 교체를 사용할 때 URL 경로와 상태를 모두 별도의 인수로 지정하거나 단일 위치 유사 객체에 모든 것을 첫 번째 인수로 포함할 수 있다.

this.props.router.push('/some/path?the=query')

또는 단일 위치 유사 객체를 사용하여 URL과 상태를 모두 지정할 수 있다.이것은 위의 예와 같다.

this.props.router.push({
  pathname: '/some/path',  //path
  search: '?the=query' // query param named 'search'
})

참고 - 물론 이.props.router가 실제로 react-router api의 history 객체인지 확인하십시오.

리액터 v4+로는 이 작업을 할 수 없었다.그러나 다음과 같은 것이 효과가 있다.

//I.e. add navigate using the history stack and pass context as the 2nd parameter
this.props.history.push('/takeTest', {
  subjectsList: this.props.subjectsList.filter(f => f.isChecked === true)
})

대상 컴포넌트에 데이터를 전달하는 가장 좋은 방법, 코드를 복사하여 붙여넣기만 하면 마법을 볼 수 있다, 나는 또한 자세히 설명했다.


react-router-dom v6에서는 후크를 대신 사용할 수 있다는 점을 기억하십시오.

버전 5.x

첫번째와 두번째 구성요소가 있다고 가정해 봅시다.첫 번째는 두 번째 구성요소를 대상으로 하는 링크를 가지고 있다.

링크가 있는 첫 번째 구성 요소 링크를 클릭하면 내 경우와 같이 대상 경로로 이동:"/details".

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

export default function firstComponent() {
return(
<>
    <Link to={{
      pathname: '/details',
      state: {id: 1, name: 'sabaoon', shirt: 'green'}
    }} >Learn More</Link>
</>
)
}

이제 두 번째 구성 요소에서 다음과 같이 전달된 개체에 액세스할 수 있다.

import React from 'react'


export default class Detials extends React.Component{

    constructor(props){
        super(props);
        this.state={
            value:this.props.location.state,
        }

    }


alertMessage(){
       console.log(this.props.location.state.id);
    }

render(){
return (

    <>
     {/* the below is the id we are accessing */}

      hay! I am detail no {this.props.location.state.id} and my name is 
      {this.props.location.state.name}

      <br/>
      <br/>

 {/* press me to see the log in your browser console */}
<button onClick={()=>{this.alertMessage()}}>click me to see log</button>

    </>

    )
}

}

참고:react-router-dom의 버전 6에서는 useLocation 후크를 사용하여 반응의 기능 구성요소를 사용할 수 있고 그 다음 다른 구성요소의 해당 위치를 통해 상태 객체를 그릴 수 있지만 위의 방법은 클래스 구성요소에서 작동하지 않는다.


버전 6

react-router-dom의 후크 v6를 사용하여 동일한 목적을 달성하는 방법

두 가지 기능적 요소가 있다고 가정합시다. 첫 번째 구성 요소 A, 두 번째 구성 요소 B.구성요소 A는 구성요소 B와 데이터를 공유하고자 한다.

후크 사용: (위치 사용, Navigate 사용)

import {Link, useNavigate} from 'react-router-dom';

function ComponentA(props) {

  const navigate = useNavigate();

  const toComponentB=()=>{
navigate('/componentB',{state:{id:1,name:'sabaoon'}});
  }

  return (
   <>
<div> <a onClick={()=>{toComponentB()}}>Component B<a/></div>
</>
  );


}


export default ComponentA;

이제 우리는 구성요소 B에 있는 데이터를 얻을 것이다.

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

 function ComponentB() {

    const location = useLocation();
   
        return (

            <>
               
<div>{location.state.name}</div>

            </>
        )
    }

export default ComponentB;

쿼리 문자열로 전송하려면

this.props.router.push({
  pathname: '/payment-history',
  query: {
    email: rowData.email
  }
})

참조URL: https://stackoverflow.com/questions/42173786/react-router-pass-data-when-navigating-programmatically

반응형