![](/img/trans.png)
[英]accessing length of an array inside an object gives me 'TypeError: Cannot read property 'length' of undefined'
[英]Accessing cart.order_items.length gives TypeError: Cannot read property 'length' of undefined
TypeError: Cannot read property 'length' of undefined
当我运行我的 Django 和 ReactJs 电子商务应用程序时,这就是编译器所说的。 我需要做什么?
错误位置如cart.js
所示
> 53 | text={`${cart !== null ? cart.order_items.length : 0}`}
> ^ 54 | pointing
错误位置如Layout.js
所示
> 33 | dispatch(cartSuccess(res.data));
> ^ 34 | })
在action/cart.js
export const fetchCart = () => {
return dispatch => {
dispatch(cartStart());
authAxios
.get(orderSummaryURL)
.then(res => {
dispatch(cartSuccess(res.data));
})
.catch(err => {
dispatch(cartFail(err));
});
};
};
在Layout.js
<Menu.Menu inverted position="right">
<Dropdown
icon="filter"
loading={loading}
text={`${cart !== null ? cart.order_items.length : 0}`}
pointing
className="link item"
>
<Dropdown.Menu>
<Dropdown.Item>List Item</Dropdown.Item>
<Dropdown.Item>List Item</Dropdown.Item>
<Dropdown.Divider />
<Dropdown.Header>Header Item</Dropdown.Header>
<Dropdown.Item>
<i className="dropdown icon" />
<span className="text">Submenu</span>
<Dropdown.Menu>
<Dropdown.Item>List Item</Dropdown.Item>
<Dropdown.Item>List Item</Dropdown.Item>
</Dropdown.Menu>
</Dropdown.Item>
<Dropdown.Item>List Item</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</Menu.Menu>
您正在应用的 null 值检查位于cart
object 而不是属性order_items
上。 因此,如果cart.order_items
的值undefined
或null
发生此错误。 为了确保您没有读取未定义的长度或 null 值,您还需要对order_items
属性进行检查。
用它替换第 53 行将解决您的问题:
text={`${cart ? (cart.order_items ? cart.order_items.length : 0) : 0}`}
要更深入地了解此条件的工作原理,请参见以下代码段:
const cart0 = null const cart1 = undefined const cart2 = {} const cart3 = { order_items: null } const cart4 = { order_items: [] } const cart5 = { order_items: ["Apple", "Banana", "Pineapple"] } function cartLength(detail, cart) { console.log( detail, cart? cart.order_items? cart.order_items.length: "cart.order_items is undefined or null": "Cart undefined or null" ) } cartLength("Cart 0: ", cart0) cartLength("Cart 1: ", cart1) cartLength("Cart 2: ", cart2) cartLength("Cart 3: ", cart3) cartLength("Cart 4: ", cart4) cartLength("Cart 5: ", cart5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.