2017-10-29 11 views
0

React Router v4에서 /items/:id과 같은 경로 경로의 유효성을 검사하는 방법을 찾아야합니다. ItemPage 구성 요소 또는 Redirect 구성 요소를 로그인 페이지로 렌더링하기 전에이 항목이 데이터베이스에 있는지 (즉, 약속 또는 비동기 호출이 필요한지) 확인하고 싶습니다. 나는 https://reacttraining.com/react-router/web/example/auth-workflow의 패턴을 따르려고했지만 유효성 검사에 비동기 호출이 필요하지 않습니다. 나는 내가 Route PARAM의 비동기 유효성 검사를 할 수 있습니다 어떻게 Objects are not valid as a React child (found: [object Promise]).를 얻을React Router v4에서 URL 매개 변수 확인

처럼 뭔가를 할 때?

답변

2

업데이트 : 두 가지 방법을 시도했습니다.

높은 주문 구성 요소 :

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; 

을 사용하려면, 내가 가진 그 길을 위해 사용 된 구성 요소를 포장 : 나는이 개 높은 순서 구성 요소, AuthenticatedRouteValidatedRoute을 생성 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와 함께 갔다.