Respect Router v4 - 현재 경로를 얻는 방법
표시하려고 합니다.title
에<AppBar />
현재 경로에서 어떻게든 전달되는 경로입니다.
리액트 라우터 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 />
?
react-router 5.1 릴리스에는 useLocation이라는 후크가 있으며, 이 후크는 현재 위치 개체를 반환합니다.이 기능은 현재 URL을 알아야 할 때 도움이 됩니다.
import { useLocation } from 'react-router-dom'
function HeaderView() {
const location = useLocation();
console.log(location.pathname);
return <span>Path : {location.pathname}</span>
}
리액트 라우터 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;
}
}
react 템플릿을 사용하는 경우 react 파일의 끝은 다음과 같습니다.export default SomeComponent
고차 구성 요소(흔히 "HOC"라고 함)를 사용해야 합니다.withRouter
.
먼저 Import가 필요합니다.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 를 참조해 주세요.
react-router 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>
);
}
다음은 다음을 사용한 해결 방법입니다.history
더 읽기
import { createBrowserHistory } from "history";
const history = createBrowserHistory()
내부 라우터
<Router>
{history.location.pathname}
</Router>
Con 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}`)
React Router(v4)의 작성자는 특정 사용자를 달래기 위해 Router HOC를 추가했다고 생각합니다.그러나 렌더링 소품만 사용하여 소품들을 통과시키는 단순한 PropesRoute 컴포넌트를 만드는 것이 더 나은 접근법이라고 생각합니다.이것은 라우터와 같이 컴포넌트를 「접속」하지 않기 때문에 테스트하기 쉽습니다.네스트된 컴포넌트를 Router로 감싸면 재미가 없어집니다.또 다른 장점은 이 패스를 사용하여 원하는 소품을 통과시켜 루트로 이동할 수 있다는 것입니다.다음은 렌더 프로포트를 사용한 간단한 예입니다(웹 사이트 https://reacttraining.com/react-router/web/api/Route/render-func)(src/components/components/components/components/companets/companets-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;
usage: (루트 파라미터(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 } />
더하다
import {withRouter} from 'react-router-dom';
그런 다음 구성 요소 내보내기를 변경합니다.
export default withRouter(ComponentName)
그런 다음 다음을 사용하여 구성 요소 자체 내에서 직접(프로젝트 내의 다른 항목에 손대지 않고) 경로에 액세스할 수 있습니다.
window.location.pathname
테스트 대상: "버전": "5.1.2"
언급URL : https://stackoverflow.com/questions/42253277/react-router-v4-how-to-get-current-route
'programing' 카테고리의 다른 글
WPF 앱과 Winform의 비즈니스 앱의 장점 (0) | 2023.04.09 |
---|---|
Select-String에서 캡처된 그룹을 가져오려면 어떻게 해야 합니까? (0) | 2023.04.09 |
XML 문자열을 사전으로 변환하는 방법 (0) | 2023.04.04 |
큰 json 파일(윈도우)을 열 수 있는 JSON 뷰어가 있습니까? (0) | 2023.04.04 |
워드프레스 사이트에서 X-Frame-Options 헤더를 설정하는 방법 (0) | 2023.04.04 |