componentDidMount没有被调用,似乎根本无法正常工作

时间:2020-01-30 22:54:00

标签: javascript reactjs react-redux react-router react-dom

我尝试了很多事情。相同的代码在我的其他项目中运行,但在当前项目中无效

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import getProductCategories from '../../redux/actions/productCategoryAction'
import "./ProductCategory.css"
export class ProductCategory extends Component {
    static propTypes = {
        productCategories: PropTypes.array.isRequired
    }
    componentDidMount() {
        console.log('Mounted!');
        this.props.getProductCategories();
    }
    render() {
        return (
            <div className="main-card-body">
                <div className="main-card-container">
                    {this.props.productCategories.map((pc, i) => {
                        return (
                            <div key={i} className="main-card-card" >
                                <div className="main-card-face main-card-face1">
                                    <div className="main-card-content">
                                        <img src={pc.image} alt={pc.alt} />
                                    </div>
                                </div>
                                <div className="main-card-face main-card-face2">
                                    <div className="main-card-content">
                                        <h3> {pc.title}</h3>
                                        <p>{pc.description}</p>
                                    </div>
                                </div>
                            </div>
                        )
                    })}
                </div>
            </div>
        )
    }
}

const mapStateToProps = state => ({
    productCategories: state.productCategory.productCategories
})

const mapDispatchToProps = dispatch => {
    return {
        getProductCategories: () => {
            dispatch(getProductCategories())
        }
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(ProductCategory)

尝试不使用mapDispatchToProps作为

export default connect(mapStateToProps, {getProductCategories})(ProductCategory)

componentDidMount失败,没有任何错误,也没有显示console.log字符串。

尽管我反复核对了我仍然无法解决的所有手段。 enter image description here

找到答案,这一切都要感谢Michalis Garganourakis和cubrr 在App.js中,我正在导入带有花括号的基于类的组件“ ProductCategory”。导入时没有大括号就可以了,因为我将其导出为“默认导出”

再次感谢Michalis Garganourakis和cubrr

Cubrr刚开始就回答了这个问题。我花了很多时间来理解这个愚蠢的东西:D:D

1 个答案:

答案 0 :(得分:3)

根据您添加的图片,该错误似乎发生在render函数上,因此componentDidMount从未因为这个确切原因而被触发。

请尝试检查this.props.productCategories是否存在,然后再尝试在其上使用.map()。这应该允许render函数成功运行,然后将根据react的lifecycle method order

触发componentDidMount
this.props.productCategories && this.props.productCategories.map((pc, i) ...

此外,尝试删除第一行的export,仅保留最后一行的export default,同时还要使用connect HOC,例如:

class ProductCategory extends Component { 

// ...

}


export default connect(mapStateToProps, mapDispatchToProps)(ProductCategory)
相关问题