代码似乎没问题,但它给出了这个错误。它说类型错误:无法在 React 项目中读取 null 的属性“长度”。我已经发布了下面的代码。我正在使用 React Js 来构建它。 请帮忙。
import React, {useEffect} from 'react'
import { Link } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { Row, Col, ListGroup, Image, Form, Button, Card } from 'react-bootstrap'
import Message from '../components/Message'
import { addToCart } from '../actions/cartActions'
function CartScreen({ match, location, history }) {
const productId = match.params.id
const qty = location.search ? Number(location.search.split('=')[1]) : 1
const dispatch = useDispatch()
const cart = useSelector(state => state.cart)
const { cartItems } = cart
useEffect(() => {
if (productId){
dispatch(addToCart(productId, qty))
}
}, [dispatch, productId, qty])
return (
<Row>
<Col md={8}>
<h1>Shopping Cart</h1>
{cartItems.length === 0 ? (
<Message variant='info'>
Your cart is empty <Link to='/'>Go Back</Link>
</Message>
) : (
<ListGroup variant='flush'>
</ListGroup>
)}
</Col>
</Row>
)
}
export default CartScreen
最佳答案
如错误所述,这只是因为您的 cartItems 为 null
。
变量可以为 null 并在 1 秒后定义,但是当变量为 null 时会出现此错误,因此您永远不会看到没有 null 值的变量。
这是解决问题的三种方法。
1)
{cartItems?.length === 0 ? ( // add a ?. to check if variable is null
<Message variant='info'>
Your cart is empty <Link to='/'>Go Back</Link>
</Message>
) : (
<ListGroup variant='flush'>
</ListGroup>
)}
{cartItems && cartItems.length === 0 ? ( // you check if the var is defined before check the length
<Message variant='info'>
Your cart is empty <Link to='/'>Go Back</Link>
</Message>
) : (
<ListGroup variant='flush'>
</ListGroup>
)}
function CartScreen({ match, location, history }) {
// ...
// add a conditional render
if (!cartItems) return <p>Loading...</p>
return (
<Row>
<Col md={8}>
<h1>Shopping Cart</h1>
{cartItems.length === 0 ? (
<Message variant='info'>
Your cart is empty <Link to='/'>Go Back</Link>
</Message>
) : (
<ListGroup variant='flush'>
</ListGroup>
)}
</Col>
</Row>
)
}
关于javascript - 类型错误:无法在 React 项目中读取 null 的属性 'length',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67716998/