我有URL: /user/Jd5Egbh...
我使用react-router-dom进行导航。我创建了一个UserDetails组件。
我使用mapStateToProps
来获取这样的url params:
function mapStateToProps({ users }, ownProps) {
return { user: users[ownProps.match.params.uid]};
}
它工作正常,但我想保护此路由并仅允许经过身份验证的用户访问。
在其他组件中,我使用withAuthorization
组件并通过重构来组成以保护路线。
我尝试将这两个功能结合起来,如下所示:
export default compose(
withAuthorization(authCondition),
connect(mapStateToProps, { fetchUser })
)(UserDetails);
但ownProps
函数中的undefined
为mapStateToProps
如果我使用compose保护路线,如何访问URL参数?
EDIT1:
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;