저는 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>
이 경우의 경험 법칙은 <Link />
먼저 사용하는 것 입니다. 특히 성능 때문에 생각합니다.
답변
이제 react-router를 사용하여 연결할 v15.1
수 있습니다 useHistory
. 이것은 매우 간단하고 명확한 방법입니다. 다음은 소스 블로그의 간단한 예입니다.
import { useHistory } from "react-router-dom";
function BackButton({ children }) {
let history = useHistory()
return (
<button type="button" onClick={() => history.goBack()}>
{children}
</button>
)
}
모든 기능 구성 요소 및 사용자 지정 후크 내에서 사용할 수 있습니다. 그리고 예, 이것은 다른 후크와 동일한 클래스 구성 요소에서는 작동하지 않습니다.
여기 https://reacttraining.com/blog/react-router-v5-1/#usehistory에서 이에 대해 자세히 알아보십시오.
답변
react router dom 라이브러리 useHistory를 사용할 수도 있습니다.
`
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
`
답변
가장 간단한 방법 중 하나 : 다음과 같이 Link를 사용합니다.
import { Link } from 'react-router-dom';
<Link to={`your-path`} activeClassName="current">{your-link-name}</Link>
전체 div 섹션을 링크로 포함하려면 :
<div>
<Card as={Link} to={'path-name'}>
....
card content here
....
</Card>
</div>
답변
또한, 수 Redirect
(가) 내부 Route
로 다음과 같습니다. 이것은 잘못된 경로를 처리하기위한 것입니다.
<Route path='*' render={() =>
(
<Redirect to="/error"/>
)
}/>