无法在 reactJs 中读取 null 的属性(读取 'length')
Cannot read properties of null (reading 'length') in reactJs
我已经被这个错误卡住了一个小时了,我似乎没有解决它。我错过了什么?数组映射上的可选链接不应该解决这个问题吗?
<h2>Cart Items</h2>
<div>
{cartItems?.length === 0 && <div>Cart is empty</div>}
</div>
{cartItems?.map((e) => (
<div key={e.id} className="row">/*error is on this line
<div className='col-2'>{e.name}</div>
<div className='col-2'>
{e.qty} x {e.qty*e.price.toFixed(2)}kr
</div>
</div>
))}
我认为 optional-chaining 确保 cartItems
不是 null
但这并不意味着可能 null
数组中的值。
例如:[{ a: 1 }, null]
有效但在映射期间读取属性将失败。
我会确保 cartItems
干净。
错误不是在映射期间抛出,而是在读取 cartItems 数组上的 .length 属性时抛出。
我已经被这个错误卡住了一个小时了,我似乎没有解决它。我错过了什么?数组映射上的可选链接不应该解决这个问题吗?
<h2>Cart Items</h2>
<div>
{cartItems?.length === 0 && <div>Cart is empty</div>}
</div>
{cartItems?.map((e) => (
<div key={e.id} className="row">/*error is on this line
<div className='col-2'>{e.name}</div>
<div className='col-2'>
{e.qty} x {e.qty*e.price.toFixed(2)}kr
</div>
</div>
))}
我认为 optional-chaining 确保 cartItems
不是 null
但这并不意味着可能 null
数组中的值。
例如:[{ a: 1 }, null]
有效但在映射期间读取属性将失败。
我会确保 cartItems
干净。
错误不是在映射期间抛出,而是在读取 cartItems 数组上的 .length 属性时抛出。