React中的扩展类与Redux

时间:2017-10-15 11:14:30

标签: javascript reactjs redux

我有以下问题:我有一个react类(dashboardContainer),仅当用户登录时才可见。此类(dashboardContainer)由其他类(授权)扩展,授权类检查用户是否已登录并获取如果数据不在状态,则为用户数据。这两个类都使用react-redux connect,但是当我执行它时会抛出下一个错误:

  

未捕获的TypeError:无法读取属性'存储'未定义的       在DashboardContainer.Connect(connectAdvanced.js:122)       在新的DashboardContainer(DashboardContainer.jsx:57)       在eval(ReactCompositeComponent.js:294)       at measureLifeCyclePerf(ReactCompositeComponent.js:75)       在ReactCompositeComponentWrapper._constructComponentWithoutOwner(ReactCompositeComponent.js:293)       在ReactCompositeComponentWrapper._constructComponent(ReactCompositeComponent.js:279)       在ReactCompositeComponentWrapper.mountComponent(ReactCompositeComponent.js:187)       at Object.mountComponent(ReactReconciler.js:45)       在ReactCompositeComponentWrapper.performInitialMount(ReactCompositeComponent.js:370)       在ReactCompositeComponentWrapper.mountComponent(ReactCompositeComponent.js:257)

这是代码

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做了新的反应并且我不知道我是否做得正确或是否有其他方法可以做到这一点。

3 个答案:

答案 0 :(得分:3)

由于您还将子类连接到商店,因此无需扩展已连接的组件,而是扩展这样的简单类:

// ...rest of code export class AuthorizedComponent extends Component { // ... rest of code

在定义Dashboard类时将其导入:

import {Authorized} from '../Authorized/Authorized'

现在DashboardContainer构造函数不会尝试执行连接的AuthorizedComponent的任何魔法,而只会执行您定义的代码。

答案 1 :(得分:1)

确保使用Provider以将状态传递给子组件。 您定义的容器可能没有对它的引用,这可能是您收到错误的原因:

  

无法读取未定义的属性'store'   DashboardContainer.Connect

伪示例:

<Provider store={store}>
    <App/>
</Provider>, document.getElementById('app'))

相关的有趣article

答案 2 :(得分:0)

您的已连接的DashboardContainer道具未正确设置。 react-redux使用propscontext获取store并将其传递给子组件。从react-redux

中查看此行
this.store = props[storeKey] || context[storeKey]  
//storeKey is 'store' and as props are undefined you are getting the error

您的道具未正确设置,因为您正在扩展另一个connected(react-redux)组件。我不知道背后的确切原因,但会尝试找到它并更新我的答案。

如果你没有使用DashboardContainer的构造函数来调用super以外的任何东西。然后你可以删除它。或者使DashboardContainer延长React.Component

修改 React建议您不要将inheritance用于组件,而应使用compositionhttps://reactjs.org/docs/composition-vs-inheritance.html

所以你可以尝试这样的事情。

class AuthorizedComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  ...
  ...
  async componentDidMount(){
    ...      
    ...        
    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

        this.setState({authorized: true});
        console.log('authorized')
        console.log(user)
        console.log('----------')
    }
  }

  render() {
    this.state.authorized
      ? <DashboardContainer />
      : <span>Show some another component</span>
  }
}