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

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

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

import React, { useState } from "react";
import Header from "./Header";
import Footer from "./Footer";
import Note from "./Note";
import CreateArea from "./CreateArea";

function App() {
  const [notes, setNotes] = useState([]);

  function handleClick(note) {
    setNotes(function (prevItems) {
      return [...prevItems, note];
    });
    console.log("Hlllo");
    event.preventDefault();
  }

  function handleDelete(indexItem) {
    setNotes(function (prevItems) {
      notes.filter(function (note, index) {
        console.log(indexItem)
        return (index = indexItem)
      });
    });
  }

  return (
    <div>
      <Header />
      <CreateArea handleClick={handleClick} />
      {notes.map(function (note, index) {
        return (
          <Note
            key={index}
            indexItem={index}
            title={note.title}
            content={note.content}
            delete={handleDelete}
          />
        );
      })}

      <Footer />
    </div>
  );
}

export default App;

这是创建区域文件,

import React, { useState } from "react";

    function CreateArea(props) {
      const [note, setNote] = useState({
        title: "",
        content: ""
      });

      function handleChange(event) {
        const { name, value } = event.target;
        setNote(function (prevValue) {
          return {
            ...prevValue,
            [name]: value
          };
        });
      }

      return (
        <div>
          <form>
            <input
              onChange={handleChange}
              name="title"
              placeholder="Title"
              value={note.title}
            />
            <textarea
              onChange={handleChange}
              name="content"
              placeholder="Take a note..."
              rows="3"
              value={note.content}
            />
            <button
              onClick={function () {
                {
                  props.handleClick(note);
                }
              }}
            >
              Add
            </button>
          </form>
        </div>
      );
    }

    export default CreateArea;

这是记录文件,

import React from "react";

function Note(props) {
  return (
    <div className="note">
      <h1>{props.title}</h1>
      <p>{props.content}</p>
      <button
        onClick={function () {
          props.delete(props.indexItem);
        }}
      >
        DELETE
      </button>
    </div>
  );
}

export default Note;
yvt65v4c

yvt65v4c1#

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

setNotes(function (prevItems) {
  return notes.filter(function (note, index) {
    console.log(indexItem)
    return index === indexItem
  });
});

相关问题