React Router를 사용하여 페이지를 리디렉션하는 가장 좋은 방법은 무엇입니까?
저는 React Router를 처음 접했고 페이지를 리디렉션하는 방법이 너무 많다는 것을 알게되었습니다.
사용
browserHistory.push("/path")import { browserHistory } from 'react-router'; //do something... browserHistory.push("/path");사용
this.context.router.push("/path")class Foo extends React.Component { constructor(props, context) { super(props, context); //do something... } redirect() { this.context.router.push("/path") } } Foo.contextTypes = { router: React.PropTypes.object }React Router v4에는
this.context.history.push("/path")및this.props.history.push("/path"). 세부 정보 : React Router v4에서 History에 푸시하는 방법
이 모든 옵션이 너무 혼란 스럽습니다. 페이지를 리디렉션하는 가장 좋은 방법이 있습니까?
실제로 사용 사례에 따라 다릅니다.
1) 권한이없는 사용자로부터 경로를 보호하고 싶습니다.
이 경우 호출 된 구성 요소를 사용 <Redirect />하고 다음 논리를 구현할 수 있습니다.
import React from 'react'
import { Redirect } from 'react-router-dom'
const ProtectedComponent = () => {
if (authFails)
return <Redirect to='/login' />
}
return <div> My Protected Component </div>
}
그러나 <Redirect />예상 한 방식으로 작업하려면 구성 요소의 렌더링 메서드 내부에 배치하여 결국 DOM 요소로 간주되어야합니다. 그렇지 않으면 작동하지 않습니다.
2) 특정 작업 후 리디렉션을 원합니다 (항목 생성 후 가정 해 봅시다)
이 경우 역사를 사용할 수 있습니다
myFunction() {
addSomeStuff(data).then(() => {
this.props.history.push('/path')
}).catch((error) => {
console.log(error)
})
또는
myFunction() {
addSomeStuff()
this.props.history.push('/path')
}
역사에 액세스하려면라는 HOC와 구성 요소를 래핑 할 수 withRouter당신이 그것으로 구성 요소를 포장 할 때 패스, match location및 history소품. 자세한 내용은 withRouter 에 대한 공식 문서를 참조하십시오.
구성 요소가 구성 요소의 자식 인 <Route />경우 <Route path='/path' component={myComponent} />구성 요소를 withRouter <Route />패스 match location및 history자식 으로 래핑 할 필요가없는 것과 같은 것 입니다.
3) 일부 요소 클릭 후 리디렉션
여기에는 두 가지 옵션이 있습니다. history.push()onClick 이벤트에 전달하여 사용할 수 있습니다.
<div onClick={this.props.history.push('/path')}> some stuff </div>
또는 <Link />구성 요소 를 사용할 수 있습니다.
`<Link to='/path' > some stuff </Link>`
I think rule of thumb with this case is (I suppose especially beceause of performance) try to use <Link /> first
'Program Club' 카테고리의 다른 글
| Java 스트림 toArray ()는 특정 유형의 배열로 변환 (0) | 2020.11.27 |
|---|---|
| React JS index.js 파일이 id 참조를 위해 index.html에 연결하는 방법은 무엇입니까? (0) | 2020.11.27 |
| C #의 코드로 네트워크 설정 (IP 주소, DNS, WINS, 호스트 이름)을 어떻게 변경할 수 있습니까? (0) | 2020.11.27 |
| 동일한 폴더에서 동일한 어셈블리의 다른 버전 사용 (0) | 2020.11.27 |
| 이 Ruby 객체에 동일한 작업을 수행하는 것처럼 보이는 to_s 및 inspect 메서드가 모두있는 이유는 무엇입니까? (0) | 2020.11.27 |