【发布时间】: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