我有以下问题:我有一个反应类(dashboardContainer),该类仅在用户登录时可见。该类(dashboardContainer)由其他类(授权)扩展,授权类检查用户是否登录并获取用户数据如果数据不在状态中。这两个类都使用react-redux connect,但是当我执行它时会抛出下一个错误:
这是代码
import React,{Component} from 'react'
import PropTypes from 'prop-types'
import lodash from 'lodash'
import auth from '../../../utils/localStorage'
import {browserHistory} from 'react-router'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import * as userActions from '../../../actions/userActions'
import * as appActions from '../../../actions/appActions'
class AuthorizedComponent extends Component {
constructor(props){
super(props)
}
async componentDidMount(){
const { routes } = this.props; // array of routes
const { router } = this.props;
console.log(this.props.userActions)
//check if user is logged (token in localstorage)
if (!auth.loggedIn() ) browserHistory.push('/login')
if(this.props.user == null ){
//get user
const response = await this.props.userActions.getUserByToken()
//get all roles available for this route
const user = await response
console.log('authorized')
console.log(user)
console.log('----------')
}
}
}
function mapStateToProps(state){
return{
user: state.user
}
}
function mapDispatchToProps(dispatch){
return {
userActions: bindActionCreators(userActions, dispatch),
appActions: bindActionCreators(appActions, dispatch)
}
}
export default connect( mapStateToProps , mapDispatchToProps )(AuthorizedComponent)
//export default AuthorizedComponent
这是DashboardContainer类:
import React from 'react'
import PropTypes from 'prop-types'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import Dashboard from './Dashboard'
import HeaderContainer from '../Header/HeaderContainer'
import Authorized from '../Authorized/Authorized'
import * as userActions from '../../../actions/userActions'
import * as appActions from '../../../actions/appActions'
class DashboardContainer extends Authorized {
constructor(props) {
super(props)
}
render() {
return (<div className="">
<HeaderContainer />
<Dashboard
itemActive={'dashboard'}/>
</div>)
}
}
function mapStateToProps(state) {
return {
app: state.app,
sidebar: state.sidebar
}
}
function mapDispatchToProps(dispatch) {
return {
userActions: bindActionCreators(userActions, dispatch),
appActions: bindActionCreators(appActions, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(DashboardContainer)
我最近刚在Redux上工作并使用react,我不知道自己做得是否正确,或者是否有其他方法可以做到这一点。
最佳答案
由于还将子类也连接到商店,因此无需扩展连接的组件,而无需扩展像这样的简单类:// ...rest of codeexport class AuthorizedComponent extends Component {// ... rest of code
并在定义仪表板类时像这样导入它:import {Authorized} from '../Authorized/Authorized'
现在,DashboardContainer
构造函数将不会尝试执行连接的AuthorizedComponent
的任何魔术,而仅尝试执行您定义的代码。