업데이트 : 두 가지 방법을 시도했습니다.
높은 주문 구성 요소 :
import React, { Component } from "react";
import { Redirect } from "react-router-dom";
let AuthenticatedRoute = ComposedComponent => class extends Component {
render() {
if (!sessionStorage.jwt) {
return <Redirect to={{
pathname: '/login',
state: { from: this.props.location }
}}/>
}
return <ComposedComponent {...this.props} />
}
}
export default AuthenticatedRoute;
그리고
import React, { Component } from "react";
import { Redirect } from "react-router-dom";
let ValidatedRoute = ComposedComponent => class extends Component {
state = {
isValid: true
}
async componentDidMount() {
this.setState({
isValid: await this.props.validator(this.props.match.params.id)
})
}
render() {
if (!this.state.isValid) {
return <Redirect to={{
pathname: this.props.redirect,
state: { from: this.props.location }
}}/>
}
return <ComposedComponent {...this.props} />
}
}
export default ValidatedRoute;
을 사용하려면, 내가 가진 그 길을 위해 사용 된 구성 요소를 포장 : 나는이 개 높은 순서 구성 요소, AuthenticatedRoute
및 ValidatedRoute
을 생성 AuthenticatedRoute(ValidatedRoute(component))
. 이점은 인증 된 라우트와 유효성이 검증 된 라우트를 깔끔하게 정리할 수 있지만 라우터 파일이 아닌 구성 요소 자체에서 수행되어야한다는 것입니다. 방금 Router
을 정기적으로 사용했습니다.
<Route exact path="/list/:id" render={(props) => <ProtectedComponent
validator={Validator}
redirect='/'
{...props}
/>
} />
다른 옵션은 PrivateRoute
구성 요소를 만드는 것이 었 : 같은 경로의 파일에 호출 보였다
import React, { Component } from "react";
import { Redirect, Route } from "react-router-dom";
class PrivateRoute extends Component {
state = {
authenticated: true,
validated: true
}
async componentDidMount() {
if (this.props.validator) {
this.setState({
validated: await this.props.validator(this.props.computedMatch.params.id)
});
}
}
render() {
if (this.props.authenticate && !sessionStorage.jwt) {
return <Redirect to={{
pathname: '/login',
state: { from: this.props.location }
}}/>
}
if (!this.state.validated) {
return <Redirect to={{
pathname: this.props.redirect,
state: { from: this.props.location }
}}/>
}
return <Route {...this.props} />
}
}
export default PrivateRoute;
을 그리고 그것은 같은 호출했다 : 아직도
<PrivateRoute exact path="/list/:id"
authenticate={true}
component={ProtectedComponent}
validator={validator}
redirect='/'
/>
꽤 안티 패턴 느낌과 React-Router-V4 문서는별로 없습니다. 나는 조금 더 조직 된 느낌이 들었 기 때문에 HOC와 함께 갔다.