删除项目时,如何自动重新反应组件?
我正在尝试在我的应用中实现删除功能,但是当我单击删除按钮时,该项目确实会删除,但该页面并未立即启动。我仍然必须手动刷新页面才能查看更新的项目列表。有没有办法在我点击删除按钮后立即自动授予该页面?这是我的代码:
import React, {useState, useEffect, useRef} from 'react';
import Header from './Header';
import Footer from './Footer';
import Note from './Note';
import CreateArea from './CreateArea';
import axios from 'axios';
function App() {
const [notes, setNotes] = useState([]);
useEffect(() => {
axios.get('http://localhost:4000/').then((response) => {
setNotes(response.data);
});
console.log(notes);
}, []);
const deleteItem = (id) => {
axios
.delete('http://localhost:4000/delete/' + id)
.then(() => {
setNotes((previousValue) => {
return previousValue.filter(({_id}) => {
return _id !== id;
});
});
});
};
return (
<div>
<Header />
<CreateArea />
{notes.map((item, index) => (
<Note
key={item._id}
id={item._id}
noteTitle={item.title}
noteContent={item.content}
onDelete={deleteItem}
/>
))}
<Footer />
</div>
);
}
export default App;
I am trying to implement a delete functionality in my app, but when I click on the delete button, the item does get deleted but the page is not rerendered right away. I still have to manually refresh the page to see the updated list of items. Is there a way to automatically rerender the page as soon as I hit the delete button? Here is my code:
import React, {useState, useEffect, useRef} from 'react';
import Header from './Header';
import Footer from './Footer';
import Note from './Note';
import CreateArea from './CreateArea';
import axios from 'axios';
function App() {
const [notes, setNotes] = useState([]);
useEffect(() => {
axios.get('http://localhost:4000/').then((response) => {
setNotes(response.data);
});
console.log(notes);
}, []);
const deleteItem = (id) => {
axios
.delete('http://localhost:4000/delete/' + id)
.then(() => {
setNotes((previousValue) => {
return previousValue.filter(({_id}) => {
return _id !== id;
});
});
});
};
return (
<div>
<Header />
<CreateArea />
{notes.map((item, index) => (
<Note
key={item._id}
id={item._id}
noteTitle={item.title}
noteContent={item.content}
onDelete={deleteItem}
/>
))}
<Footer />
</div>
);
}
export default App;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我从未见过
usestate
之前接听回调的设置。您能以这种方式更改删除处理程序:
I haven't seen the setter of
useState
taking a callback before.Could you try to change your delete handler this way:
当DeleteItem运行完整和解决时,创建前面状态以计数更改,将前孔状态传递给使用效率的依赖项,在前官态更改时再次获取:
Create forceRender state to count change when the function of deleteItem run complete and resolve, pass forceRender state to dependencies of useEffect, make it fetch again when forceRender state change: