Javascript 如何将setState与另一个函数同步
下面的代码是我目前正在处理的代码。它所做的是接收一个文件作为用户输入,并发送一个axios post请求,通过Spring Boot后端,传递的文件将存储在我的PC的C驱动器中的一个文件夹中Javascript 如何将setState与另一个函数同步,javascript,reactjs,asynchronous,synchronous,setstate,Javascript,Reactjs,Asynchronous,Synchronous,Setstate,下面的代码是我目前正在处理的代码。它所做的是接收一个文件作为用户输入,并发送一个axios post请求,通过Spring Boot后端,传递的文件将存储在我的PC的C驱动器中的一个文件夹中 import React from 'react' import { post } from 'axios'; class SimpleFileUpload extends React.Component { constructor(props) { super(props); th
import React from 'react'
import { post } from 'axios';
class SimpleFileUpload extends React.Component {
constructor(props) {
super(props);
this.state ={
file:null
}
this.onFormSubmit = this.onFormSubmit.bind(this)
this.onChange = this.onChange.bind(this)
this.fileUpload = this.fileUpload.bind(this)
}
onFormSubmit(e){
e.preventDefault() // Stop form submit
this.fileUpload(this.state.file).then((response)=>{
console.log(response.data);
})
}
onChange(e) {
const chosenFile = e.target.files[0];
this.setState({file:chosenFile});
}
fileUpload(file){
const url = 'http://localhost:8080/report/uploadFile';
const formData = new FormData();
formData.append('file',file)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
return post(url, formData,config)
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
<h1>File Upload</h1>
<input type="file" onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
)
}
}
export default SimpleFileUpload
但这种方式的问题是,即使没有单击Upload
按钮,post请求也会被发送
我试图通过添加以下两种方法,用wait
功能包装setState
setStateSynchronous(stateUpdate){
return new Promise(
this.setState({file:stateUpdate})
)
}
async callSynchSetState(stateUpdate){
await this.setStateSynchronous(stateUpdate);
}
并将onChange
方法如下所示进行了修改,但它不起作用
onChange(e) {
const chosenFile = e.target.files[0];
//this.setState({file:chosenFile});
this.callSynchSetState(chosenFile);
/*this.fileUpload(chosenFile).then((response)=>{
console.log(response.data);
}) */
}
只有在单击“上载”按钮时,才可以发送所选文件。您尝试包装
设置状态并不是完全错误的。你只需要写得更简洁
而不是
setStateSynchronous(stateUpdate){
return new Promise(
this.setState({file:stateUpdate})
)
}
async callSynchSetState(stateUpdate){
await this.setStateSynchronous(stateUpdate);
}
,只需像这样包装setState
async awaitSetState(stateUpdate){
await this.setState({file:stateUpdate})
}
,然后像这样在onChange
方法中调用该方法
onChange(e) {
const chosenFile = e.target.files[0];
this.awaitSetState(chosenFile);
}
只需在setState
前面使用wait
或使用回调。这更容易。在setState
前面使用await
的问题是我遇到了一个错误,比如不能在异步函数之外使用关键字“await”
。类似way的回调函数是我在原始帖子中展示的,但正如我提到的,问题是即使不按Upload
按钮也会发送post请求。我想做的(也写在原始帖子中)是,仅当按下Upload
按钮时,才允许用户发送帖子请求。这样,用户就可以在同一渲染周期内选择文件并单击submit按钮,这样提交处理程序的状态还没有更新?这就是我的理解吗?不,用户在选择文件后没有时间单击提交按钮。用户可以选择文件,但即使在单击“提交”按钮之前,文件也会通过post请求发送。我想做的是,只有当按下提交按钮时,才会发送post请求。这就是您的初始代码的作用,所以您是说输入的onChange
正在触发表单提交吗?还是发生了什么事?这就解决了问题!我真的很感激你能给出这样的答案:)
onChange(e) {
const chosenFile = e.target.files[0];
this.awaitSetState(chosenFile);
}