更新:2つのアプローチを試しました。
高次コンポーネント:私は2つの高次成分、AuthenticatedRoute
とValidatedRoute
作成:それらを使用するには
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(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と一緒に行きました。