开发者问题收集

获取“未捕获的 TypeError:无法读取未定义的属性(读取‘Items’)”[关闭]

2022-04-25
1902

我正在处理的一个 React 项目出现此错误“Expenses.js:8 Uncaught TypeError: 无法读取未定义的属性(读取‘Items’)”,我不知道为什么我总是收到此错误。我对 REACT 完全陌生。任何帮助都非常感谢

这是我的文件代码

App.js

import Expenses from "./components/Expenses";
 function App() {
  const expenses = [
    {
      id: "e1",
      title: "Toilet Paper",
      amount: 94.12,
      date: new Date(2020, 7, 14),
    },
    { id: "e2", title: "New TV", amount: 799.49, date: new Date(2021, 2, 12) },
    {
      id: "e3",
      title: "Car Insurance",
      amount: 294.67,
      date: new Date(2021, 2, 28),
    },
    {
      id: "e4",
      title: "New Desk (Wooden)",
      amount: 450,
      date: new Date(2021, 5, 12),
    },
  ];

  return (
    <div>
      <h2>Let's get started!</h2>
      <Expenses Items={expenses} />
    </div>
  );
}

export default App;

Expense.js

import ExpenseItem from "./ExpenseItem";
import "./Expenses.css";

function Expenses(props) {
  return (
    <div className="expenses">
      <ExpenseItem
        title={props.Items[0].title}
        amount={props.Items[0].amount}
        date={props.Items[0].date}
      />
      <ExpenseItem
        title={props.Items[1].title}
        amount={props.Items[1].amount}
        date={props.Items[1].date}
      />
      <ExpenseItem
        title={props.Items[2].title}
        amount={props.Items[2].amount}
        date={props.Items[2].date}
      />
      <ExpenseItem
        title={props.Items[3].title}
        amount={props.Items[3].amount}
        date={props.Items[3].date}
      />
    </div>
  );
}

export default Expenses();
2个回答

要解决该错误,您应该将 export default Expenses(); 更改为 export default Expenses;

您还应该以这种方式重构代码

import ExpenseItem from "./ExpenseItem";
import "./Expenses.css";

function Expenses(props) {
  return (
    <div className="expenses">
      {props.Items.map((item, i) => <ExpenseItem
        key={i}
        title={item.title}
        amount={item.amount}
        date={item.date}
      />)}
    </div>
  );
}

export default Expenses;
R4ncid
2022-04-25

没关系。我找到答案了。

在我比较了 App.js 和 Expenses.js 之后,我发现我对 Expenses.js 的 export default 写错了(应该只是 export default Expenses;)

这个问题已经解决了

Lax1177
2022-04-25