React Router v4-현재 경로를 얻는 방법?


180

나는 표시 할 title에 <AppBar />그 어떻게 든 현재의 경로에서 전달됩니다.

React Router v4 <AppBar />에서 현재 경로를 title소품 으로 전달 하는 방법은 무엇입니까?

  <Router basename='/app'>
    <main>
      <Menu active={menu} close={this.closeMenu} />
      <Overlay active={menu} onClick={this.closeMenu} />
      <AppBar handleMenuIcon={this.handleMenuIcon} title='Test' />
      <Route path='/customers' component={Customers} />
    </main>
  </Router>

사용자 정의에서 사용자 정의 제목을 전달하는 방법이 prop에은 <Route />?


답변:


74

반응 라우터의 5.1 릴리스에는 useLocation 이라는 후크 가 있으며 현재 위치 객체를 반환합니다. 현재 URL을 알아야 할 때마다 유용 할 수 있습니다.

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

function HeaderView() {
  let location = useLocation();
  console.log(location.pathname);
  return <span>Path : {location.pathname}</span>
}


6
이것은 라우터 DOM 내부에서만 사용할 수 있습니다 (예 : 라우터가 사용되는 클래스 / 기능적 구성 요소가 아닌 chid 구성 요소). 그것은 분명 수 있지만, 나 같은 초보자에 :-) 나는 모든 오류 "useContext가 정의되어 있지 않습니다"시간 얻고 있었다 없습니다
— BennyHilarious

라우터 redirect가 사용 된 경우에도 작동하지 않습니다 . 이것은 리디렉션 전에 경로를 읽을 것입니다
— Sonic Soul

이 답변에 감사드립니다 ...
— bellabelle

211

리액터 라우터 4에서 현재 경로는- this.props.location.pathname입니다. 그냥 this.props확인하십시오. 여전히 보이지 않으면 location.pathname데코레이터를 사용해야합니다 withRouter.

이것은 다음과 같이 보일 수 있습니다.

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

const SomeComponent = withRouter(props => <MyComponent {...props}/>);

class MyComponent extends React.Component {
  SomeMethod () {
    const {pathname} = this.props.location;
  }
}

14
항상 그렇지는 않습니다. react-router4를 사용하면 컴포넌트가 일부 중첩 된 경로 (나중에 경로를 확장 함)와 관련하여 상위 레벨로 렌더링되는 경우 WithRouter 내부의 location.pathname은 다음과 다릅니다.window.location.pathname
— maioman

3
React 컴포넌트 외부에서 프로그래밍 방식으로 가져 오는 방법은 무엇입니까?
— trusktr

78

반응 파일의 끝이 다음과 같은 반응의 템플릿 export default SomeComponent을 사용하는 경우 상위 컴포넌트 (보통 "HOC"라고 함)를 사용해야합니다 withRouter.

먼저 다음 withRouter과 같이 가져와야합니다 .

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

다음으로을 사용 하려고 합니다withRouter . 구성 요소의 내보내기를 변경하여이를 수행 할 수 있습니다. 에서 (으) export default ComponentName로 변경하고 싶을 수 있습니다 export default withRouter(ComponentName).

그런 다음 소품에서 경로 및 기타 정보를 얻을 수 있습니다. 구체적으로 location,, match및 history. 경로 이름을 추출하는 코드는 다음과 같습니다.

console.log(this.props.location.pathname);

https://reacttraining.com/react-router/core/guides/philosophy : 추가 정보가 포함 된 유용한 문서를 참조 하십시오.


그러나 당신은 어떻게 완전한 URL을 얻습니까?
— Tessaracter

18

다음을 사용하는 솔루션이 history 있습니다.

import { createBrowserHistory } from "history";

const history = createBrowserHistory()

라우터 내부

<Router>
   {history.location.pathname}
</Router>

3
반응 기능 경로에있는 우리에게는이 대답이 가장 합리적입니다. 이러한 this.props....우리의 귀에 소음 그냥 뭐든간에.
— KhoPhi

17

반응 라우터 v5 에는 useLocation 이라는 후크 가 있으며 HOC 또는 기타 항목이 필요하지 않습니다. 매우 간결하고 편리합니다.

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

const ExampleComponent: React.FC = () => {
  const location = useLocation();  

  return (
    <Router basename='/app'>
      <main>
        <AppBar handleMenuIcon={this.handleMenuIcon} title={location.pathname} />
      </main>
    </Router>
  );
}

이 답변의 등급은 훨씬 높아야합니다. 후크를 사용하는 것이 다른 솔루션보다 훨씬 쉽고 직관적입니다 (RR v5의 경우)
— BrDaHa

10

React Router (v4)의 저자는 특정 사용자를 달래기 위해 Router HOC로 추가했다고 생각합니다. 그러나 더 나은 접근 방식은 render prop을 사용하고 해당 props를 전달하는 간단한 PropsRoute 구성 요소를 만드는 것입니다. withRouter와 같이 구성 요소를 "연결"하지 않으므로 테스트하기가 더 쉽습니다. 라우터로 묶인 많은 중첩 구성 요소를 사용하면 재미 없을 것입니다. 또 다른 이점은 경로에 원하는 소품을 통해이 패스를 사용할 수도 있다는 것입니다. 다음은 render prop을 사용하는 간단한 예입니다. (웹 사이트 https://reacttraining.com/react-router/web/api/Route/render-func 의 정확한 예 ) (src / components / routes / props-route)

import React from 'react';
import { Route } from 'react-router';

export const PropsRoute = ({ component: Component, ...props }) => (
  <Route
    { ...props }
    render={ renderProps => (<Component { ...renderProps } { ...props } />) }
  />
);

export default PropsRoute;

사용법 : (라우트 매개 변수 (match.params)를 얻으려면이 구성 요소를 사용할 수 있으며 그 매개 변수는 전달됩니다)

import React from 'react';
import PropsRoute from 'src/components/routes/props-route';

export const someComponent = props => (<PropsRoute component={ Profile } />);

또한이 방법으로 원하는 추가 소품을 전달할 수 있습니다.

<PropsRoute isFetching={ isFetchingProfile } title="User Profile" component={ Profile } />

3
이 솔루션을 코드 펜으로 바꿀 수있는 방법이 있습니까? 더 정확한 솔루션을 사용하고 싶지만 실제로 구현 방법을 이해하지 못합니다.
— LAdams87

7

가지고 콘 Posidielov가 말했다, 현재 경로에 존재한다 this.props.location.pathname.

그러나 키 (또는 이름)와 같은보다 구체적인 필드를 일치 시키려면 matchPath 를 사용 하여 원래 경로 참조를 찾을 수 있습니다 .

import { matchPath } from `react-router`

const routes = [{
  key: 'page1'
  exact: true,
  path: '/page1/:someparam/',
  component: Page1,
},
{
  exact: true,
  key: 'page2',
  path: '/page2',
  component: Page2,
},
]

const currentRoute = routes.find(
  route => matchPath(this.props.location.pathname, route)
)

console.log(`My current route key is : ${currentRoute.key}`)

0

더하다

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

그런 다음 구성 요소 내보내기를 변경하십시오.

export default withRouter(ComponentName)

그런 다음 다음을 사용하여 구성 요소 자체 내에서 직접 경로에 액세스 할 수 있습니다 (프로젝트의 다른 것을 건드리지 않고).

window.location.pathname

"version": "5.1.2"로 2020 년 3 월에 테스트되었습니다.


이것에 대해 확실하지 않습니다. 물론 현재 경로 이름을 제공하지만 새 페이지로 이동해도 변경되지 않습니다.
— alex
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.