如何在反应中访问地图中另一个对象内的对象

How to access an object inside another object in a map in react

react.js 有时很复杂,我试图访问状态信息,我有一个数组,里面有一个对象,在这个对象中,还有另一个对象叫价格,在最后一个对象也有一个叫 price 的 属性,当我尝试在地图函数中获取此信息时,代码中断了,这是我的地图代码:(错误行在 ****** ) 错误显示如下:Uncaught TypeError: Cannot read properties of undefined (reading 'price')

products.map((item) => {
                    return (
                        <MainContainer onMouseEnter={() => onEnter(item.id)} key={item.id}>
                            <Card>
                                <TopContainer>
                                    <p>163892</p>
                                    <h2>{item.name}</h2>
                                    <Icons>
                                        <svg clip-rule="evenodd" fill-rule=</svg>
                                        <InfoOutlinedIcon/>
                                    </Icons>
                                </TopContainer>
                                <hr/>
                                <MidContainer>
                                    <img src='https://cfarma-public.s3-sa-east-1.amazonaws.com/images/nexfar-product-default-image.jpg'/>
                                    <div>
                                        <p>Base</p>
****************************************<p>Nexfar<br/>R${item.price.price}</p>********************
                                    </div>
                                    <div></div>
                                    <div></div>
                                    <div></div>
                                    <div></div>
                                </MidContainer>
                            </Card>
                        </MainContainer>
                    );
                }) 

this image shows how the objects structure is

谢谢大家!

如评论中所述,

问题是您的数组中的一个或多个元素没有 .price.price 属性,这会导致类型错误,因为它不存在。

要解决此问题,您可以 item?.price?.price

可选的链接运算符 (?.) 使您能够读取位于连接对象链深处的 属性 的值,而无需检查链中的每个引用是否有效。

查看更多:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining