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

Viv*_*vek 2 javascript typeerror reactjs

代码看起来没问题,但是却出现了这个错误。它说 TypeError: Cannot read property 'length' of null in React Project. 我已经发布了下面的代码。我正在使用 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 
Run Code Online (Sandbox Code Playgroud)

Mel*_*ynx 11

就像错误所说,这只是因为您的 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>
)}
Run Code Online (Sandbox Code Playgroud)
{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>
)}
Run Code Online (Sandbox Code Playgroud)
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>
    )
}
Run Code Online (Sandbox Code Playgroud)