我尝试在从网页中删除项目后重新呈现 DOM。我是 React 新手,我正在努力让它发挥作用。它看起来像这样:
我想要它做的是,当您单击粉红色垃圾桶时,该卡应该从 DOM 中删除,而无需刷新。
这就是代码的样子(我排除了不相关的代码):
const card = (props) => {
function deleteItem() {
fetch('/api/v1/story/'+props.storyID,{
method: 'DELETE',
})
.then(response => response.json())
.then(response => {
if(response['response'] == "success"){
//this is where i would want it to rerender the DOM
}
})
}
return (
<div className="deleteItem" onClick={deleteItem}>
</div>
)
};
export default card;
我希望有人能帮助我解决这个问题。提前致谢!
最佳答案
您应该将此删除函数拉至保存卡片列表的父组件。然后将该函数作为 props 向下传递,并使用要删除的卡片的 id 从子组件中调用它。如果没有看到您的代码,很难给出准确的解决方案,这是一个近似的解决方案。
/* parent */
function deleteItem(id) {
fetch('/api/v1/story/'+id,{
method: 'DELETE',
})
.then(response => response.json())
.then(response => {
if(response['response'] == "success"){
this.setState({ stories: this.state.stories.filter(s => s.storyId !== id) })
}
})
}
return (
<Card onDelete={deleteItem} />
)
const card = (props) => {
const deleteItem = () => props.onDelete(props.storyId)
return (
<div className="deleteItem" onClick={deleteItem}>
</div>
)
}
关于javascript - 删除项目后尝试重新渲染 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56496463/