【问题标题】:Extended class in React with ReduxReact 中的扩展类与 Redux
【发布时间】:2018-03-27 00:51:18
【问题描述】:

我有以下问题:我有一个反应类(dashboardContainer),只有在用户登录时才可见。这个类(dashboardContainer)由其他类(授权)扩展,授权类检查用户是否登录并获取如果数据未处于状态,则返回用户数据。这两个类都使用 react-redux connect 但是当我执行它时会引发下一个错误:

未捕获的类型错误:无法读取未定义的属性“存储” 在 DashboardContainer.Connect (connectAdvanced.js:122) 在新的 DashboardContainer (DashboardContainer.jsx:57) 在 eval (ReactCompositeComponent.js:294) 在 measureLifeCyclePerf (ReactCompositeComponent.js:75) 在 ReactCompositeComponentWrapper._constructComponentWithoutOwner (ReactCompositeComponent.js:293) 在 ReactCompositeComponentWrapper._constructComponent (ReactCompositeComponent.js:279) 在 ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:187) 在 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 的新人并做出了反应,我不知道我是否做得正确,或者是否有其他方法可以做得很好。

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

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

    无法读取未定义的属性“存储”在 DashboardContainer.Connect

    伪例子:

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

    相关有趣article

    【讨论】:

    • 是的,我使用提供者
    • 好的,请将供应商编码器添加到您的问题中。顺便说一句...尝试确保将商店正确传递给提供者。我希望它有帮助:)
    【解决方案2】:

    您连接的DashboardContainer 的道具设置不正确。而react-redux 使用propscontext 获取store 并将其传递给子组件。请参阅react-redux library 中的这一行

    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>
      }
    }
    

    【讨论】:

      【解决方案3】:

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

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

      并在定义 Dashboard 类时像这样导入它:

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

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

      【讨论】:

        猜你喜欢
        • 2018-12-02
        • 2020-04-06
        • 2020-05-09
        • 2017-09-21
        • 1970-01-01
        • 2011-10-31
        • 1970-01-01
        • 2016-12-14
        • 1970-01-01
        相关资源
        最近更新 更多