首页 > 解决方案 > 无法从 map 和 forEach 函数中遍历 props 数据

问题描述

当我记录产品时,我能够在控制台窗口中获取数据,但无法从array 对象“产品”中遍历数据。我已经尝试过map函数和forEach函数。数据通过 props 来自 redux 状态,并通过componentWillReceiveProps我调用setState函数的位置保存到组件状态中。

请帮助解决此问题。欢迎任何建议!

此外,当在代码中添加调试器断点时,我无法在控制台窗口中获取数据,但是当我从代码中删除调试器断点时,我能够在控制台窗口中看到数据。

import React from 'react';
import {connect} from 'react-redux';
import {fetchProduct} from '../actions/UploadAction';
import ProductCrudList from './ProductCrudList'

class ProductCrud extends React.Component {
    constructor(props){
        super(props);
        this.state={
            products:[],
            x:1,
            test:[{value:1},{value:2}]
        }
    }
    componentWillMount = () =>{
        this.props.fetchProduct();
    }
    componentWillReceiveProps=(nextProps)=>{
        if(this.props!=nextProps){
            this.setState((state)=>({products: nextProps.products}));
        }
    }
    render(){
        // debugger
        const {products, test, x} = this.state;
        console.log(products);
        products.forEach(p=>{
            console.log(p);
        })

        return (
            <div>
                <div className="">
                    <h2 style={{textAlign:'center', margin:'20px'}}>PRODUCTS</h2>
                    {   

                    }
                    {/* <ProductCrudList products={products} /> */}
                </div>
                {/* <h1>Working</h1> */}
            </div>
        )
    }
}
const mapStateToProps = (state) => {
    console.log(state);
    return { 
        products: state.products.product
    }
}







const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        fetchProduct: () => {
            dispatch(fetchProduct())
        }
    }
}


export default connect(mapStateToProps, mapDispatchToProps)(ProductCrud);

添加了一张图片,您可以在其中看到显示对象数组的控制台窗口

图片

标签: reactjsforeachreact-propsmap-functionreact-state

解决方案


推荐阅读