3

我有这个URL: /user/Jd5Egbh... 我使用 react-router-dom 进行导航。我制作了一个 UserDetails 组件。我mapStateToProps用来获取这样的 url 参数:

function mapStateToProps({ users }, ownProps) {
   return { user: users[ownProps.match.params.uid]};
}

它工作正常,但我想保护这条路线并只允许经过身份验证的用户访问。

在其他组件中,我使用一个withAuthorization组件并从重组中组合来保护路由。

我尝试将这两个功能结合起来,如下所示:

export default compose(
  withAuthorization(authCondition),
  connect(mapStateToProps, { fetchUser })
)(UserDetails);

但在功能ownProps_undefinedmapStateToProps

如果我使用 compose 来保护路由,如何访问 URL 参数?

编辑1:

import React from 'react';
import { connect } from 'react-redux';
import { compose } from 'recompose';
import { withRouter } from 'react-router-dom';

import { firebase, db, auth } from '../firebase';

const withAuthorization = (condition) => (Component) => {
  class WithAuthorization extends React.Component {
    componentDidMount() {
      firebase.auth.onAuthStateChanged(authUser => {
        if (!condition(authUser)) {
          this.props.history.push('/');
        } else {
          db.onceGetUser(authUser.uid).then(snapshot => {
              let user_data = snapshot.val();
              if (!user_data.admin) {
                auth.doSignOut();
              }
          });
        }
      });
    }

    render() {
      return this.props.authUser ? <Component /> : null;
    }
  }

  const mapStateToProps = (state) => ({
    authUser: state.auth.authUser,
  });

  return compose(
    withRouter,
    connect(mapStateToProps),
  )(WithAuthorization);
}

export default withAuthorization;
4

0 回答 0