programing

리액트 라우터에서 이전 경로를 검출하시겠습니까?

instargram 2023. 3. 3. 16:50
반응형

리액트 라우터에서 이전 경로를 검출하시겠습니까?

리액트 라우터를 사용하고 있습니다.이전 페이지(동일한 앱 내)를 발신지에서 검출하고 싶다.라우터는 컨텍스트에 있습니다.단, 라우터 오브젝트에 "이전 경로"나 이력 등의 속성은 표시되지 않습니다.제가 그걸 어떻게 합니까?

다음 명령을 사용하여 상태를 전달할 수 있습니다.<Link>컴포넌트(이 경우 패스명):

<Link to={{pathname: '/nextpath', state: { prevPath: location.pathname }}}>Example Link</Link>

그 후, 에 액세스 할 수 있습니다.prevPath부터this.props.location.state다음 컴포넌트에서

이전 페이지가 무엇인지 확인하는 대신 다른 각도에서 문제에 접근하십시오.현재 페이지를 소품으로 이동하려는 구성요소 또는 링크에 전달합니다.

history.push 또는 링크를 클릭하는 이전 페이지 또는 컴포넌트에서 현재 페이지의 상태를 추가합니다.

history.push(`/device/detail`, { from: 'device detail page' } );

그러면 이전 페이지가 사용하던 것에 액세스할 수 있습니다.history.location.state.from

에 이전 경로를 저장할 수 있습니다.componentWillReceiveProps라이프 사이클 방식이 논리는 의 트러블 슈팅 섹션에 기재되어 있는 예에 매우 가까운 것입니다.react-router문서를 참조하십시오.

<Route component={App}>
  {/* ... other routes */}
</Route>

const App = React.createClass({
  getInitialState() {
    return { prevPath: '' }
  },

  componentWillReceiveProps(nextProps) {
    if (nextProps.location !== this.props.location) {
      this.setState({ prevPath: this.props.location })
    }
  }
})

그리고 최근에는 주(州)에서 접속합니다.

사용하시는 경우react-router-reduxreact-syslog-syslogx에 의해 디스패치되는 이벤트에 후크하는 리듀서를 작성할 수 있습니다.

export default function routerLocations(state = [], action) {
  switch (action.type) {
    case "@@router/LOCATION_CHANGE":
      return [...state, action.payload]
    default:
      return state;
  }
}

기능 컴포넌트의 스테이트리스로 이전 패스로 이동하려면 react-routeruseHistory 훅을 사용합니다.상세한 것에 대하여는, https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/hooks.md#useroutematch 를 참조해 주세요.

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

function demo () {
    let history = useHistory();
    const goToPreviousPath = () => {
        history.goBack()
    }
    return (
      <div>
        <Button
          onClick={goToPreviousPath}
        >
          Back
        </Button>
      </div>
    ):
}

를 사용하고 있는 경우<Redirect />컴포넌트를 추가할 수 있습니다.from추가되는 특성location.state컴포넌트랜다이렉트 하는 컴포넌트.

// in the redirecting component
<Redirect
to={{
  pathname: '/login',
  state: { from: location }
}}
/>

//in the other component you redirected to
...
const { location } = props.location.state;
...

사용.context이전 버전을 저장할 수 있습니다.location경로 이름:

const RouterContext = React.createContext();

const RouterProvider = ({children}) => {
  const location = useLocation()
  const [route, setRoute] = useState({ //--> It can be replaced with useRef or localStorage
    to: location.pathname,
    from: location.pathname //--> previous pathname
  });

  useEffect(()=> {
    setRoute((prev)=> ({to: location.pathname, from: prev.to}) )
  }, [location]);
  
  return <RouterContext.Provider value={route}>
    {children}
  </RouterContext.Provider>
}

그 후 일부 컴포넌트에서는RouterProvider:

const route = useContext(RouterContext);
//...
<Link to={route.from}>
  Go Back
</Link>

또는

history.push(route.from);

주의:RouterContext아래에 있어야 한다Router컴포넌트 및 사용할 수 있는 상태를 업데이트하지 않을 경우useRef대신.지속성이 필요한 경우localStorage

다음을 사용하여 백스택을 구축하고 청취할 수 있습니다.history.listen바로 그 역할을 하는 갈고리가 있습니다.

import { Location } from 'history';
import { useEffect, useState } from 'react';
import { useHistory } from 'react-router';

const useBrowserBackStack = () => {
  const history = useHistory();
  const [backStack, setBackStack] = useState<Location[]>([]);
  useEffect(() => {
    history.listen((location, action) => {
      setBackStack(backStack => {
        switch (action) {
          case 'POP':
            return backStack.slice(0, backStack.length - 1);
          case 'PUSH':
            return [...backStack, location];
          case 'REPLACE':
            return [...backStack.slice(0, backStack.length - 1), location];
        }
      });
    });
  }, [setBackStack, history]);
  return backStack;
};

export default useBrowserBackStack;

그런 다음 다음과 같이 최상위 컴포넌트에서 사용합니다.

const backStack = useBrowserBackStack();

리액트 라우터 v6을 사용하는 사용자의 경우 Navigate 컴포넌트, Link 컴포넌트 또는 useNavigate 훅을 사용하여 이전 URL을 다음 컴포넌트에 전달할 수 있습니다.

리다이렉트 컴포넌트

// with Navigate component (same as with Link component):
const location = useLocation();
...
<Navigate to="/nextpath" state={ { from: location } } />
...


// with useNavigate hook:
const navigate = useNavigate();
const location = useLocation();
....
navigate("/nextpath", { state: { from: location } });
...

리다이렉트한 컴포넌트

...
const location = useLocation();
let from = location.state?.from?.pathname;
...

이 답변은 @AlexandrLazarev와 유사한 접근방식을 사용하지만 React Hooks를 통해 구현합니다.이렇게 하면 경로에 대한 모든 변경 내용이 시작 방법에 관계없이 캡처됩니다.이전 경로 값은 최상위 컴포넌트 상태로 저장되며, 다음으로 자녀에게 소품으로 전달할 수 있습니다.또한 Redux와 같은 글로벌 상태 프로바이더를 사용하는 경우에는 스토어에 추가할 수 있습니다.

import { useEffect, useState } from 'react'

cont App = ({ location }) => {
  const [currentPath, setCurrentPath] = useState(null);
  const [previousPath, setPreviousPath] = useState(null);

  useEffect(() => {
    if (location.pathname !== currentPath) {
      setPreviousPath(currentPath);
      setCurrentPath(location.pathname);
    }
  }, [location.pathname]);
}

마크업에서의 실장은 다음과 같은 스니펫이 됩니다.Reach Router를 사용하고 있습니다만, React Router와 Marge 되어 있기 때문에, Reach Router에서도 동작합니다.컴포넌트에 의해location할 수 을 "자녀", "자녀", "자녀", "자녀", "자녀" 모두 사용할 수 있습니다.pathname

<Router>
  <App path="/*" />
<Router/>

컴포넌트가 재렌더되지 않고 이전 패스를 얻으려면 이 솔루션을 참조하십시오.

로케이션.js:

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


export default () => {
  const location = useLocation();
  const path = location.pathname;
  const store = window.localStorage;
  let url = '';
  let prevUrl = '';

  url = store.getItem('url');
  store.setItem('prevUrl', url);
  store.setItem('url', path);

  url = store.getItem('url');
  prevUrl = store.getItem('prevUrl');

  return { url, prevUrl };

}

다른 파일

import Location from './location.js'


const { url, prevUrl } = Location()

반응 - 소품을 사용하여 이전 경로 가져오기

console.log(props.history.location.state && props.history.location.state.from.pathname);

를 하여 리다이렉트하면<Link> OR <Redirect> ? pathname : undefined

useNavigate() 후크를 사용합니다(예: const navigate = useNavigate();).navigate() 함수를 호출하여 -1 - navigate(-1)를 전달합니다.-1로 네비게이트를 호출하는 것은 뒤로 버튼을 누르는 것과 같습니다.

const previousPageHandler = () => {
    navigate(-1);
}

react-router-v6를 사용하여 n페이지 앞뒤로 이동하는 방법을 찾으시는 분은useNavigate API,

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

const navigate = useNavigate()

이 을 '하다'에게 수 있어요.onClick a 등

<button onClick={() => navigate(-1)}>Previous</button>

음의 정수는 뒤로, 양의 정수는 앞으로입니다.

상세한 것에 대하여는, 다음의 문서를 참조해 주세요.

이전 경로가 특정 경로와 동일한 경우에만 조건부로 탐색할 수 있는 방법이 필요했습니다.기능적인 컴포넌트를 사용하면 다음과 같이 동작합니다.&&를 하다.push()가 method일 에만 .'/cart'.

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

const history = useHistory();

history.location.pathname === '/cart' && history.push('/checkout');

언급URL : https://stackoverflow.com/questions/39288915/detect-previous-path-in-react-router

반응형