【问题标题】:Higher Order Components and Authenticate Routes高阶组件和验证路由
【发布时间】:2019-05-06 20:36:59
【问题描述】:

我正在 React 中创建高阶组件并确保用户无法访问受保护的路由。一切正常,但我不确定将检查 redux 状态的代码放在哪里。目前,在下面的代码中,我已将所有代码放在 componentDidMount 中。这是因为 componentWillMount 已被弃用。这是检查的最佳位置,因为 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)

}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    假设在构造时正确的状态可用,您可以在构造函数中进行重定向:

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

    【讨论】:

      【解决方案2】:

      这就是 React Router Redirect 组件的用途:

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

      【讨论】:

        猜你喜欢
        • 2017-10-12
        • 2020-03-17
        • 2020-04-12
        • 2019-05-16
        • 1970-01-01
        • 1970-01-01
        • 2017-06-03
        • 2012-10-11
        • 1970-01-01
        相关资源
        最近更新 更多