如何映射传递给函数的 JSON 数据?

How do I map JSON data that is passed into a function?

我正在尝试获取 JSON 数据并将其传递到我的 'HistoryChart' 组件中,以尝试将日期和价格映射到两个数组中,以便我可以将它们显示在我的图表上。但是,我不断收到未定义的错误。

这里是 JSON 数据:

{
    "_id": 1,
    "name": "",
    "brand": "",
    "image": "",
    "sources": [],
    "history": [
        {
            "_id": 3,
            "price": "299.99",
            "product": 1,
            "date": "2021-07-01"
        },
        {
            "_id": 4,
            "price": "399.99",
            "product": 1,
            "date": "2021-07-08"
        },
        {
            "_id": 5,
            "price": "499.99",
            "product": 1,
            "date": "2021-07-15"
        },
        {
            "_id": 6,
            "price": "599.99",
            "product": 1,
            "date": "2021-07-22"
        },
        {
            "_id": 7,
            "price": "699.99",
            "product": 1,
            "date": "2021-07-29"
        }
    ]
}

这是我的 HistoryChart 组件:

function HistoryChart({product}) {
 
    var dates = product.history.map(function(e){ //<-- The Problem lies here where it says cannot map undefined.
        return e.date;
    });

    var prices = product.history.map(function(e){
        return e.price;
    });

    return (
        <div>
            <Line
                data={{
                    labels: dates,
                    datasets: [{
                        label: `Average Price History (ID: ${product._id})`, //<-- This part works
                        backgroundColor:/* 'transparent' */ '#00ad0e',
                        borderColor: '#00ad0e',
                        data: prices,
                    }]
                }}
                width={100}
                height={50}
                options={{ maintainAspectRatio: true }}
            />
        </div>
    )
}

我也在使用 redux 来获取数据:

const productDetails = useSelector(state => state.productDetails)
const {error, loading, product} = productDetails

并且数据像这样传递到 HistoryChart 组件中:

 <HistoryChart product={product}/>

非常感谢任何帮助,谢谢。

错误原因

由于数据来自服务器,加载需要一些时间。并且您收到未定义错误,因为您第一次想要访问尚未成功加载的对象 producthistory

解决方案

const price = product && product.history.map(//do what you want)

以这种方式使用对象的键值不会导致任何错误,因为如果未加载产品,它不会调用映射函数,当成功加载产品对象时,它将调用映射函数

抱歉,如果这不是您的主要问题,但同时当 .map 导致未定义时,最简单的调整是验证您的数组是否未定义。

所以在我的项目中我总是先检查数组是否未定义,我会用你的代码做一个例子

  function HistoryChart({product}) {
     
if (product !== undefined){
        var dates = product.history.map(function(e){ 
            return e.date;
        });

    
        var prices = product.history.map(function(e){
            return e.price;
        });
}

试试这个方法,如果可行请告诉我。