最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeError: Cannot read property 'length' of null in React Project - Stack Overflow

programmeradmin1浏览0评论

The code seems to be fine but it's giving this error. It says TypeError: Cannot read property 'length' of null in React Project. I have posted the code below. I am using React Js to build this. Help, please.

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 

The code seems to be fine but it's giving this error. It says TypeError: Cannot read property 'length' of null in React Project. I have posted the code below. I am using React Js to build this. Help, please.

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 
Share Improve this question edited Mar 9, 2022 at 14:28 Akash Kumar Verma 3,3182 gold badges18 silver badges33 bronze badges asked May 27, 2021 at 6:47 VivekVivek 3413 gold badges4 silver badges10 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 11

Like the error say, it's just because your cartItems is null.

The variable can be null and defined 1 seconde after, but when the variable is null you have this error so you never see the variable with no null value.

Here are three ways to fix your problem.

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>
    )
}

add a default value for your cartItems like an empty array in reducer or do this:

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

Your cartItems variable is probably null in the store. Try to initialize it as empty array instead.

I just put the ? before the "length", problem sovled :v ex in my code: currentItems.length > 0 => currentItems?.length > 0

发布评论

评论列表(0)

  1. 暂无评论