reactjs - 以同步方式集成两个反应函数
问题描述
我有下面的反应代码。我想以同步的方式将 handleUpdate 集成到 handleUpload 函数中,以便在函数的其余部分执行之前设置状态。我尝试了以下内容,我的编辑以粗体显示,但它似乎是异步执行的,并且在执行之前没有设置状态。谁能告诉我我需要在哪里进行更改以满足我的需求?
handleUpdate = event => {
this.setState({
selectedFile: event.target.files[0]
})
}
handleUpload = () => {
**this.handleFileChange;**
var fd = new FormData();
fd.append('file', this.state.selectedFile, this.state.selectedFile.name);
fetch('/upload', {method: 'POST', body: fd})
.then(response => {
return response.json()})
.then(result => {
console.log(result)})
.catch(function(error) {
console.log("ERROR:" + error);
});
}
解决方案
handleUpdate = event => {
this.setState({
selectedFile: event.target.files[0]
}, ()=>this.handleUpload())
}
您可以在 setState 的回调函数中调用 handleUpload 函数,以确保仅在设置 state.selectedFile 后才调用 handleUpload 函数
推荐阅读
- apache-nifi - NIFI EXECUTESCRIPT 处理器失败 - 未找到模块
- python - -m 在设置虚拟环境时使用(或有用)是什么?
- python - 通过Python按日期计算列值的范围
- r - 下载处理程序在已发布的服务器上不起作用
- apache - 为 localhost 和 LAN 连接设置 SSL
- python - 在 selenium 中使用 Xpath 找不到页面上的元素
- java - 当 SearchView 打开时隐藏 TextView
- javascript - 对输入字符串进行严格的正则表达式验证
- wordpress - 在 Wordpress 仪表板菜单中重命名插件名称
- r - emmeans (R) 仅拦截功能是否损坏?