简体   繁体   English

类型错误:无法读取未定义的属性(读取“长度”)

[英]TypeError: Cannot read properties of undefined (reading 'length')

Working my way through my first fullstack MERN app that allows a user to add multiple places to an array.完成我的第一个全栈 MERN 应用程序,它允许用户向数组添加多个位置。 Trying to map over the array to display the number of places for the user.试图通过数组 map 来显示用户的位置数。 Code works fine until I use .length , then it crashes.代码工作正常,直到我使用.length ,然后它崩溃了。

import React from 'react';

import UserItem from './UserItem';
import Card from '../../shared/components/UIElements/Card/Card';
import './UsersList.css';


const UsersList = props => {
    if (props.items.length === 0) {
        return (
            <div className="center">
                <Card>
                    <h2>No users found.</h2>
                </Card>
            </div>
        );
    }


    return (
        <ul className="users-list">
            {props.items.map(user => (
                <UserItem
                    key={user.id}
                    id={user.id}
                    image={user.image}
                    name={user.name}
                    // placeCount={user.places.length}
                    placeCount={user.places}
                />
            ))}
        </ul>
    );


};

export default UsersList;

The full error stack:完整的错误堆栈:

Uncaught TypeError: Cannot read properties of undefined (reading 'length')
The above error occurred in the <UsersList> component:

  
Consider adding an error boundary to your tree to customize error handling behavior.

Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
  

I did a keyword search of .length throughout the backend and frontend files to double check the code and make sure I didn't have any typos anywhere--but for the life of me I can't figure out why adding .length isn't working.我在整个后端和前端文件中对.length进行了关键字搜索,以仔细检查代码并确保我在任何地方都没有错别字——但我一直想不通为什么添加.length不是工作。

I've gone through a few different posts on here but cannot find a working solution.我在这里浏览了几个不同的帖子,但找不到有效的解决方案。

Any insight would be greatly appreciated.任何见解将不胜感激。 For now I just commented out .length so I can keep working.现在我只是注释掉了.length这样我就可以继续工作了。 Thank you!谢谢!

You can define a default value for items to fix it.您可以为items定义一个默认值来修复它。

const UsersList = ({ items = [] }) => {
  if (items.length === 0) {
    return (
      ...
    );
  }

  return (
    <ul className="users-list">
      {items.map((user) => (
        ...
      ))}
    </ul>
  );
};

Changing this if condition from this:从这个改变这个if条件:

if (props.items.length === 0) {

To

if (!props.items?.length) {

Should work.应该管用。

Similarly if using for places,you can check using ternary operator if length exists in array of places.类似地,如果用于地点,您可以使用三元运算符检查地点数组中是否存在长度。

How?如何? Because items could possibly be null or undefined from apis, so the length property on array might be missing.因为项目可能是null或 api undefined ,所以数组的length属性可能丢失。

Moreover, using !此外,使用! Not operator would make this condition true if length of items is 0 or is null or undefined or any falsy value如果项目的长度为 0 或 null 或未定义或任何虚假值,则 Not 运算符将使此条件为真

The other answers are focusing on prop.items list but in your question you mention that you get the exception when trying to access the length of the places inside user s.其他答案集中在prop.items列表上,但在您的问题中,您提到在尝试访问user内的places长度时出现异常。

You are getting the error message because some users may not have any places listed inside them, hence, no places list -> no length property.您收到错误消息是因为某些用户可能没有在其中列出任何位置,因此没有位置列表 -> 没有长度属性。

To fix this, you need to check if the places list exists and then access its length:要解决此问题,您需要检查地点列表是否存在,然后访问其长度:

placeCount={ user.places ? user.places.length : 0 }

Here, we use a ternary operator to check if user.places exists, then we use the length, else use zero.在这里,我们使用三元运算符来检查user.places是否存在,然后我们使用长度,否则使用零。

Edit: As pointed out by Phil in the comments below, you can also use coalescing operator, which is much cleaner, like this:编辑:正如 Phil 在下面的评论中所指出的,您还可以使用合并运算符,它更简洁,如下所示:

placeCount={ user.places?.length ?? 0 }

The syntax simply translates as if user.places has a value for length, then use that value, else use zero as a default value.语法简单地翻译为好像 user.places 具有长度值,然后使用该值,否则使用零作为默认值。

Here you can use object destructuring .这里可以使用object 解构 if you are not sure whether the data will come or not.如果您不确定数据是否会到来。 JSX will always render first and after that props, so in some cases it may render empty JSX. JSX 总是先渲染然后渲染 props,所以在某些情况下它可能渲染空的 JSX。

you can make the changes in your component like this您可以像这样在组件中进行更改

const UsersList = props => {
const { items = [] } = props

    // checking whether its an array or not and have some items in it
    if (!Array.isArray(items) || items.length === 0) {
        return (
            <div className="center">
                <Card>
                    <h2>No users found.</h2>
                </Card>
            </div>
        );
    }


    return (
        <ul className="users-list">
            {items.map(user => {
              const { id = "", image = "", name = "", places = "" } = user
              return <UserItem
                key={id}
                id={id}
                image={image}
                name={name}
                // placeCount={user.places.length}
                placeCount={places}
              />
           })}
        </ul>
    );
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型错误:无法读取未定义的属性(读取“长度”) - TypeError: Cannot read properties of undefined (reading 'length') TypeError:无法读取未定义的属性(读取“长度”) - Blockchain JS - TypeError: Cannot read properties of undefined (reading 'length') - Blockchain JS 未捕获的类型错误:无法在 GoogleMapReact 读取未定义的属性(读取“长度”) - Uncaught TypeError: Cannot read properties of undefined (reading 'length') at GoogleMapReact vuejs 2 组合 api: TypeError: Cannot read properties of undefined (reading 'length') - vuejs 2 composition api: TypeError: Cannot read properties of undefined (reading 'length') 未处理的运行时错误类型错误:无法读取未定义的属性(读取“长度”) - Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'length') TYPEORM TypeError:无法读取未定义的属性(读取“长度”) - TYPEORM TypeError: Cannot read properties of undefined (reading 'length') 未捕获的类型错误:无法读取未定义的属性(读取“长度”) - Uncaught TypeError: Cannot read properties of undefined (reading 'length') TypeError:无法读取未定义(读取“长度”)JEST 测试的属性 - TypeError: Cannot read properties of undefined (reading 'length') JEST test TypeError:无法读取 null 的属性(读取“长度”) - TypeError: Cannot read properties of null (reading 'length') 无法读取代码框中未定义的属性(读取“长度”) - Cannot read properties of undefined (reading 'length') in codesandbox
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM