javascript TypeError:无法读取React项目中null的属性“length”

pkwftd7m  于 2023-05-05  发布在  Java
关注(0)|答案(3)|浏览(149)

代码似乎很好,但它给出了这个错误。TypeError:无法读取React项目中null的属性“length”。我把代码贴在下面。我使用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
ppcbkaq5

ppcbkaq51#

就像错误所说的,这只是因为你的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>
    )
}
1dkrff03

1dkrff032#

为你的cartItems添加一个默认值,比如在reducer中添加一个空数组,或者这样做:

(cartItems || []).length === 0
insrf1ej

insrf1ej3#

您的cartItems变量在存储中可能为null。尝试将其初始化为空数组。

相关问题