reactjs - Best way to update component after this handleClick?
问题描述
I currently have this function in a component. It requests a delete to an api. At the end of the function however I need to update the component so that the app re-renders the display thus removing a jsx element that rendered the object that was deleted. I know forceUpdate() is not recommended but it doesn't work in this code anyway. Anyone know why? And what is the better way to implement this component update? The backend is indeed deleting the requested object and the console log works btw.
handleClick() {
const logId = this.props.log._id;
fetch(`/api/logs/${logId}`, {
method: 'DELETE',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: logId
})
})
.then(res => res.text())
.then(res => alert(res))
.catch(err => alert(err))
this.forceUpdate()
console.log('Deleted log"')
}
解决方案
为什么不使用 just setState
?它会自动重新渲染您的组件。
.then((res) => this.setState({ deletedId: logId }))
然后您可以通知用户指定logId
的已删除。
{this.state.deletedId && <span>deleted id: {this.state.deletedId}</span>}
推荐阅读
- .net-core - 从 API-Method 运行 xUnit-Tests
- utf-8 - JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0) ---While Tuning gpt2.finetune
- graphql - 如何在 NestJS 中热重载联邦网关
- javascript - { abortEarly: false} 在 Joi 中不起作用(在 mvc 结构中)
- entity-framework - 实体框架上下文添加有什么作用?
- parent-child - 如何限制 Rally 中项目的父类型
- python-3.x - Django 3.2.3 教程4 NoReverseMatch
- apache-flink - 在 Apache Flink 中加入 DataStreams
- reactjs - 如何在 spfx 中开发自定义设计和母版页
- bash - 如何控制作为参数之一传递给 bash 函数的重定向运算符?