【问题标题】:TypeError: Cannot read property 'length' of null in React ProjectTypeError:无法在 React Project 中读取 null 的属性“长度”
【发布时间】:2021-08-15 09:51:38
【问题描述】:

error image

代码似乎很好,但它给出了这个错误。它说:TypeError:无法在 React Project 中读取 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

【问题讨论】:

    标签: javascript reactjs typeerror


    【解决方案1】:

    就像错误说的那样,这只是因为您的 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 }) {
        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])
    
        // 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>
        )
    }
    

    【讨论】:

      【解决方案2】:

      为您的 cartItems 添加一个默认值,例如在 reducer 中添加一个空数组或执行以下操作:

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

      【讨论】:

      • 这是一个坏主意,也不是一个好的语法。 Juste cartItems?.lengh 很好。
      • 这只是一个例子。在我看来,这种情况下的最佳实践是在 reducer 中为变量添加默认值。
      • 你说得对。所以分享这个最佳实践,而不是我们的代码库中没有人想要的实践
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2018-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-20
        相关资源
        最近更新 更多