Program Club

React Router를 사용하여 페이지를 리디렉션하는 가장 좋은 방법은 무엇입니까?

proclub 2020. 11. 27. 21:40
반응형

React Router를 사용하여 페이지를 리디렉션하는 가장 좋은 방법은 무엇입니까?


저는 React Router를 처음 접했고 페이지를 리디렉션하는 방법이 너무 많다는 것을 알게되었습니다.

  1. 사용 browserHistory.push("/path")

    import { browserHistory } from 'react-router';
    //do something...
    browserHistory.push("/path");
    
  2. 사용 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
    }
    
  3. 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 locationhistory소품. 자세한 내용은 withRouter 에 대한 공식 문서를 참조하십시오.

구성 요소가 구성 요소의 자식 인 <Route />경우 <Route path='/path' component={myComponent} />구성 요소를 withRouter <Route />패스 match locationhistory자식 으로 래핑 할 필요가없는 것과 같은 입니다.

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

참고URL : https://stackoverflow.com/questions/45089386/what-is-the-best-way-to-redirect-a-page-using-react-router

반응형