[英]REACT: array.map() function not rendering components properly when dealing with an array with newly added object at 0 index
在下面的 REACT 代碼方面需要幫助。 制作一個筆記應用程序並嘗試讓它在我的筆記列表的頂部出現一個新的筆記。 當我在數組末尾添加新注釋時,我的代碼可以正常工作,但是如果我切換它以便在開頭添加它時像這樣:
const newNotes = [newNote, ...notes];
然后它會顯示所有相同的舊音符,最后一個音符重復兩次。 負責在屏幕上顯示注釋的代碼如下所示。
const listNotes = ()=>{
console.log(notes);
return notes.map((obj, index) => (
<Note
key={index}
id={obj.id}
subject={obj.subject}
text={obj.text}
date={obj.date}
handleDeleteNote={deleteNote}
/>
))
}
經過一些調試后,我注意到新列表已成功創建,並且 map 正在“成功”創建注釋組件,當我在 map ZC1C425268E68385D1AB5074C17A94F 之前將注釋打印到控制台時,它似乎表明新創建的列表很好。 但是當它到達“.map()”時,由於某種原因它沒有完全遵循列表,幾乎就像它沒有意識到列表中有一個新項目,直到它重新編寫筆記的一半。
下面是組件的完整代碼。
import React, { useState, useEffect } from "react";
import { nanoid } from "nanoid"; //allows for random IDs
import NoteSearch from "./NoteSearch"; // component that searches notes
import Note from "./Note"; // Component for saved notes
import AddNewNote from "./AddNewNote"; //Component to add new note
const NotesList = () => {
// States
const [notes, setNotes] = useState([
{
id: nanoid(),
subject: "Fruit",
text: "bananas are awesome",
date: "9/23/2022",
},
{
id: nanoid(),
subject: "ew",
text: "onions are awesome",
date: "9/24/2022",
},
{
id: nanoid(),
subject: "veggie",
text: "carrots are awesome",
date: "9/25/2022",
},
]);
// Add and Delete Note handlers
const addNote = (subject, text) => {
const date = new Date();
const newNote = {
id: nanoid(),
subject: subject,
text: text,
date: date.toLocaleDateString(),
};
const newNotes = [newNote, ...notes];
setNotes(newNotes);
};
const deleteNote = (CurrentID) => {
const newNotes = notes.filter((note)=>note.id !== CurrentID);
setNotes(newNotes);
};
//functions
const listNotes = ()=>{
console.log(notes);
return notes.map((obj, index) => (
<Note
key={index}
id={obj.id}
subject={obj.subject}
text={obj.text}
date={obj.date}
handleDeleteNote={deleteNote}
/>
))
}
// This is the notes app DOM
return (
<div className="notes-wrapper">
<NoteSearch />
<div className="all-notes">
<AddNewNote handleAddNote={addNote}/>
{
listNotes()
}
</div>
</div>
);
};
使用id作為鍵而不是索引:
<Note
key={obj.id}
id={obj.id}
subject={obj.subject}
text={obj.text}
date={obj.date}
handleDeleteNote={deleteNote}
/>
您正在動態更改列表,不鼓勵使用索引作為鍵,這可能會導致問題。
這是因為您使用索引作為鍵。 React 認為您不想卸載/重新安裝前 n 個節點(那些已經存在的節點)。 它只會更新他們的道具。 您的 Node 組件可能會在構造函數中或在組件安裝后初始化其 state 並且不會在道具更改時重新計算 state。 因此,列表不會在視覺上更新,除了最后一個新節點。
使用 id 作為鍵應該可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.