列表中的每个子项都应该有一个唯一的“key”道具。在反应应用程序中

问题描述 投票:0回答:3

我正在尝试使用 api 制作反应笔记应用程序,一切正常,但是当我添加新笔记时,我面临这个警告:列表中的每个孩子都应该有一个唯一的“key”道具。检查`Notes`的渲染方法

您可以在此处查看注释组件,

{notes.length === 0 ? (
          <p>No notes to display</p>
        ) : (
          notes.map(({ id, title, body, created }) => (
            <li className="note" key={id}>
              <div className="details">
                <p>{title}</p>
                <span>{body}</span>
              </div>
              <div className="bottom-content">
                <span>{formatDate(created)}</span>

                <div
                  className={`settings ${
                    showMenu && selectedNoteId === id ? "show" : ""
                  }`}
                >
                  <AiOutlineEllipsis
                    className="icon"
                    onClick={() => toggleMenu(id)}
                  />

                  <ul className={"menu"}>
                    <li
                      onClick={() => handleEdit({ id, title, body, created })}
                    >
                      <BiPencil />
                      Edit
                    </li>

                    <li onClick={() => toggleDeletePopup(id)}>
                      <BiTrash />
                      Delete
                    </li>
                  </ul>
                  {selectedDeleteNoteId === id && (
                    <DeletePopup
                      onCancel={handleDeleteCanceled}
                      deleteConfirmed={() => handleDeleteConfirmed(id)}
                    />
                  )}
                  {selectedEditNote && selectedEditNote.id === id && (
                    <EditNotePopup
                      note={selectedEditNote}
                      onSubmit={handleNoteUpdate}
                      onCancel={() => setSelectedEditNote(null)}
                    />
                  )}
                </div>
              </div>
            </li>
          ))
        )}

这里是添加新注释组件

return (
    <div className="newnote-popup">
      <div className="card">
        <header>
          <h3>Add a new note</h3>
          <FaTimes className={"x"} onClick={handleCancel} />
        </header>
        <form onSubmit={handleSubmit}>
          <div className="note-title">
            <label>Title</label>
            <input
              type="text"
              name="title"
              value={note.title}
              onChange={handleChange}
              maxLength={50}
              autoComplete="none"
            />
            <small className="character-count">{titleCount}/50 </small>
          </div>
          <div className="note-body">
            <label>Description</label>
            <textarea
              name="body"
              value={note.body}
              onChange={handleChange}
              placeholder="Your Note"
              maxLength={400}
            />
            <small className="character-count">{characterCount}/400 </small>
          </div>
          <div className="buttons">
            <button type="submit">Add Note</button>
          </div>
        </form>
      </div>
    </div>
  );

我搜索了这个问题,所有的解决方案都是添加唯一密钥,但我已经在代码中添加了带有 id 的密钥,所以问题是什么,谢谢。

reactjs unique-key
3个回答
1
投票

试试这个。其余代码将保持不变

notes.map(({ id, title, body, created },index) => (
            <li className="note" key={index}>

1
投票

也许您没有获得独特的

id
。就这样做吧

notes.map(({ id, title, body, created }, index) => (
    <li className="note" key={index}>
    .....
    </li>
)

0
投票

在您的代码片段中,您确实使用注释数组中的 id 属性为每个“

<li>
”元素分配一个唯一的键。这应该是正确的,并且 key prop 本身似乎没有问题。

我认为,问题可能出在代码的其他地方,可能出在添加新注释的方式上。如果您添加新注释而在渲染之前没有为其分配唯一 ID,则可能会导致错误。确保在添加新注释时,在将其呈现在列表中之前为其提供唯一的 ID。添加此代码:

// Inside your component's state
const [note, setNote] = useState({
  id: generateUniqueId(), // Use a function to generate a unique id
  title: "",
  body: "",
  created: new Date().toISOString(), // You can adjust this as needed
});

// Function to handle adding a new note
const handleSubmit = (e) => {
  e.preventDefault();
  
  // Ensure note has a unique id
  const newNote = { ...note, id: generateUniqueId() };
  
  // Add the new note to your notes array
  const updatedNotes = [...notes, newNote];
  
  // Update the state with the new notes
  setNotes(updatedNotes);
  
  // Clear the form or reset the note state for a new note
  setNote({
    id: generateUniqueId(),
    title: "",
    body: "",
    created: new Date().toISOString(),
  });
};

// Function to generate a unique id
const generateUniqueId = () => {
  return Math.random().toString(36).substr(2, 9);
};
© www.soinside.com 2019 - 2024. All rights reserved.