简体   繁体   中英

TypeError: Cannot read property 'length' of undefined in reactjs

i am facing problem when i try to return the length of array in react. the error is 'TypeError: Cannot read property 'length' of undefined'. I have put this in another child component and it work but when i tried in NavBar it just show the error.

import React from 'react';
import './NavBar.css';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCartPlus } from '@fortawesome/free-solid-svg-icons';

const NavBar = (props) => {
    const order = props.cart
    return (
        <div className='container-fluid'>
            <nav className="navbar navbar-expand-lg navbar-light  justify-content-md-between justify-content-center flex-wrap">
                <a href="/"><img src="https://i.ibb.co/NZcQbJM/logo2.png" alt="Red Onion Food"/></a>

                <div>
                    <a href="/" className='nav-item' > <FontAwesomeIcon icon={faCartPlus} /></a>
                    <a href="/" className='nav-item login'>Login</a>
                    <a href="/" className='nav-item'><button className="btn btn-danger btn-rounded">Sign Up</button></a>
                </div>
            </nav>
            <div><h6>{order.length}</h6></div>
        </div>
    );
};

export default NavBar;

I dont know what to do!!!

You need to short-circuit the render based on the existence of the array. You're trying to render the length of order before the prop is available.

Try the following:

<div><h6>{order && order.length}</h6></div>

The undefined error is because of order is not available that time , so you need to check for the presence of order and then execute.

{order ? order.length : 0}

The other answers pretty much sorted the problem out, ie you are trying to literally say undefined.length since the prop order is not defined at some stage while creating/updating the component.

But there is still a cleaner solution to it IMO - order?.length .

And the logic of what-if-not (from the answer by @arun-kumar) - could also be written as - order?.length?? 0 order?.length?? 0 or order?.length || 0 order?.length || 0 .

More on it -

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

  3. https://github.com/facebook/create-react-app/releases/tag/v3.3.0 - CRA v3.3 supports those already.

Update - The de-structuring is also a cleaner way. I've used it a lot, since it allows initialising the prop in case it is not defined, but easily could be over-written by different type of value - hence I think optional chaining has an advantage over it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM