简体   繁体   English

高阶组件和验证路由

[英]Higher Order Components and Authenticate Routes

I am creating Higher Order Components in React and making sure that user cannot access the protected routes. 我在React中创建高阶组件并确保用户无法访问受保护的路由。 Everything works fine but I am unsure where to put the code for checking the redux state. 一切正常但我不确定在哪里放置检查redux状态的代码。 Currently, in the code below I have placed all the code in componentDidMount. 目前,在下面的代码中,我已将所有代码放在componentDidMount中。 This is because componentWillMount is deprecated. 这是因为不推荐使用componentWillMount。 Is this the best place to check because componentDidMount is triggered after the component has been mounted. 这是检查的最佳位置,因为在装入组件后会触发componentDidMount。

import React, { Component } from 'react';
import { connect } from 'react-redux'

export default function(ComposedComponent) {

  class Authenticate extends Component {

    componentDidMount() {

      if(!this.props.isAuthenticated) {
        this.props.history.push('/')
      }

    }

    render() {
      return (
        <ComposedComponent {...this.props} />
      )
    }
  }

const mapStateToProps = (state) => {
  return {
    isAuthenticated: state.isAuthenticated
  }
}


return connect(mapStateToProps)(Authenticate)

}

Assuming the correct state is available at construction, you can do the redirect in the constructor: 假设构造中可以使用正确的状态,您可以在构造函数中进行重定向:

class Authenticate extends Component {
   constructor(props) {
      super(props);
      if(!props.isAuthenticated) {
         props.history.push('/')
      }
   }
...
}

This is the purpose of React Router Redirect component: 这是React Router Redirect组件的目的:

render() {
  return !this.props.isAuthenticated ? (
    <Redirect to="/" />
  ) : (
    <ComposedComponent {...this.props} />
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM