Javascript 在React中的顶部显示最新元素
我正在创建一个React应用程序。我想在顶部显示最后添加的注释 Notes是一个对象数组。正如你所看到的,我试过notes.reverse(),但不知怎么的,它不起作用。元素仍在底部添加Javascript 在React中的顶部显示最新元素,javascript,arrays,reactjs,react-native,Javascript,Arrays,Reactjs,React Native,我正在创建一个React应用程序。我想在顶部显示最后添加的注释 Notes是一个对象数组。正如你所看到的,我试过notes.reverse(),但不知怎么的,它不起作用。元素仍在底部添加 <div> {notes.reverse().map((note)=> ( <NotesCard note={note} key={note.id} setInputTe
<div>
{notes.reverse().map((note)=> (
<NotesCard
note={note}
key={note.id}
setInputText={setInputText}
setInputTitle={setInputTitle}
setNotes={setNotes}
notes={notes}
setId={setId}
/>
))
}
</div>
我还使用updateHandler函数来更新现有的便笺。单击“更新”按钮时触发。每当我在这里使用splice()或unshift()设置顶部的更新注释时,chrome停止响应,所有内容都会挂起
const updateHandler = () => {
for (var i=0; i<notes.length; i++) {
if (id===notes[i].id) {
if (inputText || inputTitle) {
notes.push(
{title:inputTitle , text: inputText, id: Math.random()*1000}
);
setNotes(notes.filter((el) => el.id !== id));
} else {
alert("Notes are Empty. Type something in textarea.");
}
}
};
setInputText("");
setInputTitle("");
setId("");
}
const updateHandler=()=>{
对于(变量i=0;i el.id!==id));
}否则{
警报(“备注为空。请在文本区域键入内容。”);
}
}
};
setInputText(“”);
setInputTitle(“”);
setId(“”);
}
我认为您应该在第一个位置添加新对象,如下所示
const submitHandler = () => {
if (inputText || inputTitle) {
setNotes([{
title: inputTitle,
text: inputText,
id: Math.random() * 1000
}, ...notes]);
} else {
alert('Notes are Empty. Type something in textarea.');
}
setInputText('');
setInputTitle('');
setId('');
};
const updateHandler = () => {
if (inputText || inputTitle) {
const newCopyNotes = notes.filter(el => el.id !== id);
setNotes([
{ title: inputTitle, text: inputText, id: Math.random() * 1000 },
...newCopyNotes
]);
} else {
alert('Notes are Empty. Type something in textarea.');
}
setInputText('');
setInputTitle('');
setId('');
};
移除反向
并正常映射
<div>
{notes.map((note)=> (
<NotesCard
note={note}
key={note.id}
setInputText={setInputText}
setInputTitle={setInputTitle}
setNotes={setNotes}
notes={notes}
setId={setId}
/>
))
}
</div>
{notes.map((note)=>(
))
}
删除背面()并将新注释添加到注释数组的顶部
首先
而不是{notes.reverse().map((note)=>(//code))}
使用{notes.map((note)=>(//code))}
秒
而不是
setNotes([
...notes,
{title:inputTitle , text: inputText, id: Math.random()*1000}
]);
使用
您还可以在向notes数组添加新对象的位置添加代码。您可以向我展示您的notes外观吗?您可以向我们展示您如何在
notes
@jaybhat中添加新元素吗?您现在不应该添加函数检查。您的id
不应该是随机的,您可以让它的值作为增量吗,可能是notes.length+1
之类的。拥有一个随机的id
等同于误用键
。我正在使用updateHandler函数来更新现有的笔记。我刚把它加在奎斯蒂诺上。在此处使用splice()或unshift()会导致浏览器挂起问题。我已更新了updateHandler的答案。我正在使用updateHandler函数更新现有便笺。我只是在问题中加了它。如何在顶部添加更新的元素。使用splice()或unshift()会导致浏览器挂起问题。如果在react记事卡组件中使用它,请检查是否已在render中直接调用update()?理想情况下,控制台中的错误消息将为“超出最大调用堆栈”。当时它没有响应,请共享代码为NotesCard调用updateI解决了问题。通过在开头添加一个项,我意外地创建了一个无限循环。我只需要再增加一次I就可以跳转到下一个元素。
setNotes([
...notes,
{title:inputTitle , text: inputText, id: Math.random()*1000}
]);
setNotes([
{title:inputTitle , text: inputText, id: Math.random()*1000},
...notes
]);