错误:无法读取未定义的react js的属性“map”

dnph8jn4  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(504)

当我删除一个项目时,它会显示“无法读取注解”,属性为“未定义”。否则,Map功能将正常工作。我认为过滤函数中有一些错误。

  1. import React, { useState } from "react";
  2. import Header from "./Header";
  3. import Footer from "./Footer";
  4. import Note from "./Note";
  5. import CreateArea from "./CreateArea";
  6. function App() {
  7. const [notes, setNotes] = useState([]);
  8. function handleClick(note) {
  9. setNotes(function (prevItems) {
  10. return [...prevItems, note];
  11. });
  12. console.log("Hlllo");
  13. event.preventDefault();
  14. }
  15. function handleDelete(indexItem) {
  16. setNotes(function (prevItems) {
  17. notes.filter(function (note, index) {
  18. console.log(indexItem)
  19. return (index = indexItem)
  20. });
  21. });
  22. }
  23. return (
  24. <div>
  25. <Header />
  26. <CreateArea handleClick={handleClick} />
  27. {notes.map(function (note, index) {
  28. return (
  29. <Note
  30. key={index}
  31. indexItem={index}
  32. title={note.title}
  33. content={note.content}
  34. delete={handleDelete}
  35. />
  36. );
  37. })}
  38. <Footer />
  39. </div>
  40. );
  41. }
  42. export default App;

这是创建区域文件,

  1. import React, { useState } from "react";
  2. function CreateArea(props) {
  3. const [note, setNote] = useState({
  4. title: "",
  5. content: ""
  6. });
  7. function handleChange(event) {
  8. const { name, value } = event.target;
  9. setNote(function (prevValue) {
  10. return {
  11. ...prevValue,
  12. [name]: value
  13. };
  14. });
  15. }
  16. return (
  17. <div>
  18. <form>
  19. <input
  20. onChange={handleChange}
  21. name="title"
  22. placeholder="Title"
  23. value={note.title}
  24. />
  25. <textarea
  26. onChange={handleChange}
  27. name="content"
  28. placeholder="Take a note..."
  29. rows="3"
  30. value={note.content}
  31. />
  32. <button
  33. onClick={function () {
  34. {
  35. props.handleClick(note);
  36. }
  37. }}
  38. >
  39. Add
  40. </button>
  41. </form>
  42. </div>
  43. );
  44. }
  45. export default CreateArea;

这是记录文件,

  1. import React from "react";
  2. function Note(props) {
  3. return (
  4. <div className="note">
  5. <h1>{props.title}</h1>
  6. <p>{props.content}</p>
  7. <button
  8. onClick={function () {
  9. props.delete(props.indexItem);
  10. }}
  11. >
  12. DELETE
  13. </button>
  14. </div>
  15. );
  16. }
  17. export default Note;
yvt65v4c

yvt65v4c1#

setNotes 应该返回一个新状态。如果你不归还任何东西。新的州将是 undefined . 然后会出现这个错误。您可以这样更新以返回新元素:

  1. setNotes(function (prevItems) {
  2. return notes.filter(function (note, index) {
  3. console.log(indexItem)
  4. return index === indexItem
  5. });
  6. });

相关问题