【问题标题】:Accessing array indices in React在 React 中访问数组索引
【发布时间】:2022-01-16 11:34:43
【问题描述】:

我对 React 和 Javascript 作为一个整体是新手。我只是想在获取后访问数组索引。我可以在文件更新后记录特定索引,但是当我刷新页面时,我收到“未定义”错误。我觉得我的状态好像做错了什么,但我对 React 的了解还不够,无法调试它。如果我尝试访问“users[0].name”,我会得到“TypeError: Cannot read properties of undefined (reading 'name') (匿名函数)。

import React, { useEffect, useState } from "react";

import { Container, Card, Divider, Typography } from "@mui/material";

const RestData = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users/")
      .then((response) => response.json())
      .then((data) => setData(data));
  }, []);

  return (
    <Container>
      {data.map((users) => {
        return (
          <Card
            data={data}
            key={users.id}
            sx={{ width: "300px", mt: 2, background: "#ff9800" }}
          >
            <Typography variant="h6" color="seagreen">
              {users.name}
            </Typography>
            <Divider />
            {users.email}
            <Divider />
            {users.company.name}
            <Divider />
            {users.phone}
            <Divider />
            {users.website}
            <Divider />
          </Card>
        );
      })}
    </Container>
  );
};

export default RestData;

【问题讨论】:

  • 什么是未定义错误?你能把整个消息贴出来吗?
  • 您想使用索引做什么?将其显示为 id?
  • 同意@theJuls 你能编辑帖子并添加欠精细的错误消息
  • TypeError: Cannot read properties of undefined (reading 'name') (anonymous function)
  • 我已经编辑了带有特定错误条件的帖子。

标签: javascript reactjs use-effect use-state


【解决方案1】:

虽然我没有在您发布的代码中看到这种情况,但您会收到该特定错误,因为您尝试访问 .name 当对象 被访问是未定义的。

我想你正在尝试做类似data[0].name 的事情。

问题是,您的 data 数组开始为空,因此如果您尝试访问空数组的任何索引,它将是 undefined,您将收到该错误。

解决方案是在访问它的索引之前确保 data 数组已经包含它的元素。

现在,有很多方法可以做到这一点。因为它似乎不是您代码的一部分,所以很难告诉您最好的方法。但这里有一对:

1- 在尝试访问该属性之前进行 if 检查:

if (data[0]) {
  console.log(data[0].name)
  // do stuff
}

2- 首先使用&amp;&amp; 运算符检查属性是否存在: 对于这种情况,只有当data[0] 为真时才会尝试访问name

console.log(data[0] && data[0].name)

3- 使用optional chaining。这是一个更好的 imo,因为它允许您跳过 if 并且只会尝试访问不是 undefined 的属性。

console.log(data[0]?.name)

所以现在把它付诸实践,这里有一个示例应用:

const App = () => {
  const [data, setData] = React.useState([]);
  React.useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users/")
      .then((response) => response.json())
      .then((data) => setData(data));
  }, []);

  console.log("data", data);
  return (
    <div>
      <div>
        <h3>Example by accessing the index directly with Optional Chaining:</h3>
        <p>{data[0] && data[0].name}</p>
      </div>
      <div>
       <h3>Example with the map</h3>
      {(data).map((d) => {
        return <p>{d.name}</p>;
      })}
      
      </div>
    </div>
  );
}


ReactDOM.render(
    <App />,
    document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>

【讨论】:

    【解决方案2】:

    由于您在渲染时获取数据,因此您没有users[0].name,所以我建议使用条件运算符?
    所以你有这样的东西

    data[0]?.name
    

    在这种情况下发生的情况是打字稿尝试访问给定索引处的属性name,如果属性为undefined,则返回null,否则返回值。

    我还做了一个快速的sandbox 进行演示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 2023-03-12
      • 2020-08-31
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      相关资源
      最近更新 更多