javascript - 在.then 中的 setState 之后,组件在 Axios 调用之后不重新渲染
问题描述
在下面的代码中,我希望组件在和ListItem
上刷新。handleOnAdd
handleOnUpdate
这些函数作为道具传递给AddItem
和EditItem
组件。
ListItem
组件item
从的App
状态获取它的 s。
它适用于handleOnDelete
,因为我添加了.then(this.handleChange())
. 我对 and 做同样的事情handleOnAdd
,handleOnUpdate
但那些不会触发重新加载....
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [{ "_id": { "$oid": "5f1fda0169e133382277a4ef" }, "title": "Blabla", "description": "adfadfd211233", "__v": 0 }]
}
this.handleOnUpdate = this.handleOnUpdate.bind(this);
this.handleOnAdd = this.handleOnAdd.bind(this);
this.handleOnDelete = this.handleOnDelete.bind(this);
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
Axios.get('http://localhost:4200/items')
.then(res => {
this.setState({ items: res.data })
})
.catch(function (error) {
console.log(error)
})
}
handleChange() {
Axios.get('http://localhost:4200/items')
.then(res => {
this.setState({ items: res.data })
})
.catch(function (error) {
console.log(error)
})
}
handleOnAdd(item) {
Axios.post('http://localhost:4200/items/add/', item)
.then(res => console.log(res.data))
.then(this.handleChange());
}
handleOnUpdate(id, item) {
Axios.post('http://localhost:4200/items/update/' + id, item)
.then(res => console.log(res.data))
.then(this.handleChange());
}
handleOnDelete(id) {
Axios.get('http://localhost:4200/items/delete/' + id)
.catch(err => console.log(err)).then(this.handleChange());
}
render() {
return (
.... Router stuff....
<Route exact path='/add' render={(props) => <AddItem {...props} handleOnAdd={(item) => this.handleOnAdd(item)} />} />
<Route path='/edit/:id' render={(props) => <EditItem {...props} handleOnUpdate={(id, item) => this.handleOnUpdate(id, item)} />} />
<Route path='/index' render={(props) => <ListItem {...props} handleOnDeleteInApp={(id) => this.handleOnDelete(id)} items={this.state.items} />} />
.... Router stuff....
);
}
}
谁能发现为什么handleOnDelete
以及随之而来的状态更改成功触发了重新渲染ListItem
,但其他功能却没有?
解决方案
.then(this.handleChange());
此代码handleChange
立即调用,然后将其结果传递给.then
. 所以这段代码不等待前几行的添加/更新/删除。如果handleOnDelete
工作正常,那么我认为这只是由于竞争条件。
您应该将所有三个函数中的这一行更改为:
.then(() => this.handleChange())
或者
.then(this.handleChange);
推荐阅读
- post - 通过 Arduino IDE 来自 IFTTT 的 HTTP 响应代码 -1
- c# - 反序列化 json 中的嵌套对象并分配给 c# 列表
- c# - 如何处理在selenium c#中弹出的窗口文件上传
- sql - 有没有办法在 Athena 的 ARRAY(ROW()) 中取消嵌套或返回所有元素?
- xcode - NSTableView 内容的自动调整大小不起作用
- android - 使用动态 URL 进行改造
- python - 如何从子流程中获取输入?
- javascript - 除了递归调用本身之外,命名一个正在分配的函数还有其他用途吗?
- azure-active-directory - 如何在安装在不同组织的 MS Teams Bot 中接收用户照片?
- laravel - 当外部 api 向我发送数据时,Laravel 中的此路由不支持 POST 方法