【发布时间】:2020-10-22 18:15:07
【问题描述】:
当用户点击按钮时,我希望应用能够
- 从输入字段读取文本
- 将其发布到 MySQL 以添加为新行
- 从 MySQL 中提取所有行(包括新行)
- 使用刚刚提取的新数据更新 react 组件状态
- 并为用户重新呈现所有数据的列表
我看到的问题是拉下所有行不包括刚刚发布的行,除非我包括手动延迟(通过 setTimeout)。
这就是我的两个函数的样子
// gets all data, updates state, thus triggering react to rerender
listWords() {
setTimeout(() => fetch("http://localhost:9000/listWords")
.then(res => res.text())
.then(res => this.setState({ wordList: JSON.parse(res)})), 2000)
}
// sends new word to the MySQL database, then kicks off the listWords process to refetch all data
addWord() {
fetch("http://localhost:9000/addWord", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
word: this.state.newWord
})
})
.then(res => res.json())
.then(this.listWords())
}
我不应该在那里有那个 setTimeout,但是当我删除它时,listWords 更新没有新发布的行。
我最好的猜测是
- 我搞砸了 promise
.then()范式,或者 - MySQL 响应我的 POST 请求,但直到 GET 完成后才真正添加行,因此错过了新行。
在再次拉取行之前,如何确保 POST 已成功完成?
我正在使用 react、express、sequelize,对于数据库,它是 docker 容器中的 MySQL。
【问题讨论】:
-
听起来像是情况 2。您是否登录了端口 9000 请求处理程序?从日志中检查(执行 2 个相应 SQL 的顺序),然后您可以验证它是否是案例 2。
标签: mysql reactjs express async-await