React实现列表中每个新增项显示对应添加时间的方法
解决方法:为笔记添加并展示创建时间
问题根源
你当前的代码存在两个核心问题:
- 笔记列表
notesList仅存储纯文本,没有保存创建日期的空间 - 渲染
Note组件时传递date={new Date()},会导致每次组件重渲染都生成新的日期,而非笔记添加时的真实时间
以下是分步修改方案:
1. 调整笔记的数据结构
把原来的字符串数组改成包含文本和创建时间的对象数组,用TypeScript的接口定义结构更清晰:
// 定义笔记的类型 interface NoteItem { text: string; createdAt: Date; } // 更新useState的初始值与类型 const [notesList, setNotesList] = React.useState<NoteItem[]>([]);
2. 修改添加笔记的逻辑
添加新笔记时,直接记录当前的日期时间:
const addNote = (): void => { setNotesList([...notesList, { text: "", createdAt: new Date() }]); };
3. 更新修改与删除笔记的逻辑
适配新的数据结构,修改时保留原有的创建时间:
const deleteNote = React.useCallback( (idx: number): void => { const newList = [...notesList]; newList.splice(idx, 1); setNotesList(newList); }, [notesList] ); const updateNote = React.useCallback( (idx: number, text: string): void => { const newList = [...notesList]; // 只更新文本,保留创建时间 newList.splice(idx, 1, { ...newList[idx], text }); setNotesList(newList); }, [notesList] );
4. 调整过滤逻辑
过滤时基于笔记的text字段进行匹配:
const getFilteredNotes = (notes: NoteItem[], query: string,) => { if (!query) { return notes; } return notes.filter((note) => note.text.includes(query)); };
5. 渲染时传递真实的创建时间
替换掉之前的new Date(),直接使用笔记对象中存储的创建时间:
filteredNotes.map((note: NoteItem, idx: number) => ( <Note onChange={updateNote} remove={deleteNote} idx={idx} text={note.text} date={note.createdAt} // 使用存储好的创建时间 key={idx} /> ))
可选优化:格式化日期显示
如果需要把日期转为更友好的格式,可以直接在渲染时处理,比如:
// 转为本地格式的字符串(如"2024/5/20 14:30:00") date={note.createdAt.toLocaleString()}
或者在Note组件内部对传入的Date对象进行格式化处理。
内容的提问来源于stack exchange,提问作者agobago
相关产品推荐
相关产品推荐

