以同步方式集成两个反应功能
Integrating two react functions in a synchronous way
我有下面的 React 代码。我想以同步方式将 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函数,确保handleUpload函数只在state.selectedFile设置后被调用
我有下面的 React 代码。我想以同步方式将 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函数,确保handleUpload函数只在state.selectedFile设置后被调用