简体   繁体   English

反应:array.map() function 在处理新添加的 object 在 0 索引处的数组时无法正确渲染组件

[英]REACT: array.map() function not rendering components properly when dealing with an array with newly added object at 0 index

Need help with the REACT code below.在下面的 REACT 代码方面需要帮助。 Making a note taking app and tried to make it so that a new note appears at the top of the list of my notes.制作一个笔记应用程序并尝试让它在我的笔记列表的顶部出现一个新的笔记。 My code works fine when I add the new note at the end of the array, but if I switch it so that when I add it in the beginning like so:当我在数组末尾添加新注释时,我的代码可以正常工作,但是如果我切换它以便在开头添加它时像这样:

const newNotes = [newNote, ...notes];

it then displays all the same old notes with the last one repeated twice.然后它会显示所有相同的旧音符,最后一个音符重复两次。 the code responsible for displaying the notes on the screen looks like this.负责在屏幕上显示注释的代码如下所示。

  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}
      />
    ))
  }

After some debugging I notice that the new list is being created successfully and the map is creating the notes components "successfully" and when I print notes to the console right before the map function it seems to show that the the newly created list is fine.经过一些调试后,我注意到新列表已成功创建,并且 map 正在“成功”创建注释组件,当我在 map ZC1C425268E68385D1AB5074C17A94F 之前将注释打印到控制台时,它似乎表明新创建的列表很好。 but when it gets to the ".map()" for some reason it's not following the list exactly, it's almost like it doesn't realize there's a new item in the list until it's halfway through redering the notes.但是当它到达“.map()”时,由于某种原因它没有完全遵循列表,几乎就像它没有意识到列表中有一个新项目,直到它重新编写笔记的一半。

full code of component below.下面是组件的完整代码。

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>
  );
};

Use id as key not index :使用id作为而不是索引

   <Note
    key={obj.id}
    id={obj.id}
    subject={obj.subject}
    text={obj.text}
    date={obj.date}
    handleDeleteNote={deleteNote}
  />

You are changing your list dynamically and it is discouraged to use index as key and may cause an issue.您正在动态更改列表,不鼓励使用索引作为键,这可能会导致问题。

React doc.: We don't recommend using indexes for keys if the order of items may change. React doc.:如果项目的顺序可能发生变化,我们不建议对键使用索引。

This is because you are using indexes as keys.这是因为您使用索引作为键。 React thinks that you don't want to unmount/remount the n first nodes (those that were already existing). React 认为您不想卸载/重新安装前 n 个节点(那些已经存在的节点)。 It will just update their props.它只会更新他们的道具。 Likely your Node component initializes its state in the constructor or after the component did mount and do not recompute the state on props changes.您的 Node 组件可能会在构造函数中或在组件安装后初始化其 state 并且不会在道具更改时重新计算 state。 As a consequence the list is not updated visually, except for the last new node.因此,列表不会在视觉上更新,除了最后一个新节点。

Using the id as key should solve the problem.使用 id 作为键应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM