리액트 라우터 2.0.0-rc5에서 현재 루트를 얻는 방법
다음과 같은 라우터가 있습니다.
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Index}/>
<Route path="login" component={Login}/>
</Route>
</Router>
달성하고 싶은 것은 다음과 같습니다.
- 사용자 리다이렉트
/login로그인하지 않은 경우 - 사용자가 에 접속하려고 했을 경우
/login이미 로그인한 경우 루트로 리다이렉트합니다./
그래서 지금 사용자 상태를 확인하려고 합니다.App의componentDidMount다음 작업을 수행합니다.
if (!user.isLoggedIn) {
this.context.router.push('login')
} else if(currentRoute == 'login') {
this.context.router.push('/')
}
문제는 현재 경로를 얻을 수 있는 API를 찾을 수 없다는 것입니다.
이 닫힌 문제는 Router를 사용하는 것이 권장된다는 것을 발견했습니다.ActiveState 믹스인과 루트핸들러는 권장되지 않는 것 같습니다.
문서를 좀 더 읽은 후 해결책을 찾았습니다.
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md
주입된 기지에 접근하기만 하면 돼location컴포넌트 인스턴스의 예를 다음에 나타냅니다.
var currentLocation = this.props.location.pathname
현재 경로는 다음을 사용하여 얻을 수 있습니다.
const currentRoute = this.props.routes[this.props.routes.length - 1];
...최저 레벨의 액티브로부터 소품에 액세스 할 수 있습니다.<Route ...>요소.
주어진...
<Route path="childpath" component={ChildComponent} />
currentRoute.path돌아온다'childpath'그리고.currentRoute.component돌아온다function _class() { ... }.
기록을 사용할 경우, 라우터는 기록에서 다음과 같은 모든 내용을 위치에 저장합니다.
this.props.location.pathname;
this.props.location.query;
알았어요?
버전 3.0.0 이후로는 다음 콜을 통해 현재 루트를 얻을 수 있습니다.
this.disc.location.pathname
샘플 코드는 다음과 같습니다.
var NavLink = React.createClass({
contextTypes: {
router: React.PropTypes.object
},
render() {
return (
<Link {...this.props}></Link>
);
}
});
2017년에 같은 문제가 발생한 사용자의 경우 다음과 같이 해결했습니다.
NavBar.contextTypes = {
router: React.PropTypes.object,
location: React.PropTypes.object
}
다음과 같이 사용합니다.
componentDidMount () {
console.log(this.context.location.pathname);
}
인App.js아래 코드를 추가하고 시도해보세요.
window.location.pathname
다음과 같이 'isActive' 프로펠러를 사용할 수 있습니다.
const { router } = this.context;
if (router.isActive('/login')) {
router.push('/');
}
isActive는 true 또는 false를 반환합니다.
리액트 라우터 2.7로 테스트 완료
동일한 방식으로 작동합니다.
...
<MyComponent {...this.props}>
<Route path="path1" name="pname1" component="FirstPath">
...
</MyComponent>
...
그런 다음 MyComponent 함수의 this.props.location.pathname에 액세스할 수 있습니다.
I am인 것을 잊고 있었습니다.) 다음 링크에서 네비게이션 바 작성 등에 대한 자세한 내용을 설명합니다.: 리액트 라우터 this.syslog.location
다음을 사용하여 경로를 캡처해 보십시오.document.location.pathname
Javascript에서 현재 URL을 부품별로 볼 수 있습니다.https://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/에서 확인하세요.
언급URL : https://stackoverflow.com/questions/35031911/how-to-get-current-route-in-react-router-2-0-0-rc5
'programing' 카테고리의 다른 글
| 리액트 훅을 내부 루프 또는 네스트 함수로 호출할 수 없는 이유는 무엇입니까? (0) | 2023.02.22 |
|---|---|
| sh: react-module: npm start 실행 후 명령을 찾을 수 없습니다. (0) | 2023.02.22 |
| SQL에서 GROUP BY/집약 기능의 혼란 (0) | 2023.02.22 |
| 스프링 및 JsonTypeInfo 주석을 사용하여 JSON을 다형 객체모델로 시리얼 해제 (0) | 2023.02.22 |
| restsharp를 사용하여 json 문자열 직렬화 해제 (0) | 2023.02.22 |