source

react-router-dom v6에서 이전 루트로 돌아가는 방법

myloves 2023. 3. 19. 19:37

react-router-dom v6에서 이전 루트로 돌아가는 방법

초기 버전에서는 이력을 사용하여 이전 경로로 돌아갈 수 있습니다.

history.goBack()

react-router-domv6를 사용하여 이를 실현하려면 어떻게 해야 합니까?

이 방법을 사용해 보세요.

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

function YourApp() {
  const navigate = useNavigate();

  return (
    <>
      <button onClick={() => navigate(-1)}>go back</button>
    </>
  );
}

V6에서는

import { useNavigate } from 'react-router-dom';
 
function App() {
  const navigate = useNavigate();
 
  return (
    <>
      <button onClick={() => navigate(-2)}>Go 2 pages back</button>
      <button onClick={() => navigate(-1)}>Go back</button>
      <button onClick={() => navigate(1)}>Go forward</button>
      <button onClick={() => navigate(2)}>Go 2 pages forward</button>
    </>
  );
}

나처럼 뒤로 이동하거나 다른 곳으로 이동할 수 없는 경우(예: 새 탭에서 링크를 여는 경우)에 v6에서 리액트 라우터를 사용하여 이력을 확인할 수 있는 방법은 없는 것 같습니다.그러나 창에 액세스할 수 있는 것 같습니다.history.state는 이력 스택의 시작점에 있는 경우 idx 속성이 0인 경우 사용합니다.

주변에 내가 마주치지 않은 몇 가지 문제가 있을 수 있지만, 그것은 나에게 효과가 있다.

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

// ...

const navigate = useNavigate();

// ...

if (window.history.state && window.history.state.idx > 0) {
    navigate(-1);
} else {
    navigate('/', { replace: true }); // the current entry in the history stack will be replaced with the new one with { replace: true }
}

이전 버전의 react-router-dom에는 함수가 있습니다.팝

다음과 같이 고객에게 연락할 수 있습니다.

const history = useHistory();
history.pop()

이제 v6에서 useNavigate 기능을 사용할 수 있습니다.

const navigate = useNavigate();
navigate(-1) // you will go one page back
navigate(-2) // you will go two pages back

리액트 라우터 링크v6에서는 델타(숫자)를 사용하는 다른 방법이 있습니다.

const BackButton = () => {
  return (
    <Link to={-1}>
      Back
    </Link>
  );
};

유감스럽게도 타이프 스크립트에 타입 오류가 있습니다.링크 컴포넌트는 숫자를 받아들일 수 없지만 동작합니다.

뒤로 이동하거나 다른 곳에서 이 작업을 수행할 수 있는 경우:

 <button onClick={() => navigate(-1) || navigate('/dashboard')}>
    Go back or Dashboard
  </button>
import { useEffect } from "react";
import {useNavigate } from "react-router-dom";// react-router-dom v6 version 

const SecondComponent = () =>{
const navigate = useNavigate();
  
useEffect(() => {
    navigate('/secondComponent')
  },[]);

// note: we must have to to provide path like this one 
/*
<Routes>
        <Route path="/" element={<FirstComponent/>} />
        <Route path="/secondComponent" element={<SecondComponent />} />
      </Routes>
*/

  return(
    <>
    <h2 >this is Second page</h2>
    </>
  )
}

export  default SecondComponent;

언급URL : https://stackoverflow.com/questions/65948671/how-to-go-back-to-previous-route-in-react-router-dom-v6