此处响应数据包含{name,details}字段。我有一个上传按钮,可以上传单个/多个文件。上传文件后,我不会刷新页面。现在,例如,我上传单个文件并显示响应。我再次上传2个文件。现在,我应该能够显示当前上传以及上一个的响应。它应采用以下格式:1.名称1详细资料12. Name2详细资料23.名称3详细信息3
this.state.list = this.state.list.concat(details);
this.state.list_name = this.state.list_name.concat(name);
< form onSubmit={this.handleSubmit} >
<label>
Upload a file: <br /><br />
<input type="file" name="file" multiple onChange{this.onChangeHandler}/>
</label>
<br /><br />
<button type="submit">
Upload</button>
</form >
<ol>
// {this.state.list_name.map((k) =>
// <li>{k} :</li>)}
//{this.state.list.map((k) =>
// <li>{k}</li>
// )}
</ol>
handleSubmit = (event) => {
event.preventDefault();
const formData = new FormData();
for (var x = 0; x < this.state.selectedFile.length; x++) {
formData.append('inputFile', this.state.selectedFile[x])
fetch('url', {
method: 'POST',
body: formData
}).then(res => {
return res.json()
})
.then((res) => {
this.setState({
details: res.data.details,
name: res.data.name
})
console.log("res data", res)
//console.log("Data is", res.data.name) //displays name in the console
})
.catch(error => console.log('ERROR message'))
}
};
我已经评论了我尝试过的代码。预先感谢。
您可以这样做
删除此
this.state.list = this.state.list.concat(details);
this.state.list_name = this.state.list_name.concat(name);
添加此
fetch('url', {
method: 'POST',
body: formData
}).then(res => {
return res.json()
})
.then((res) => {
const list = this.state.list;
list.concat(res.data.details);
const list_name = this.state.list_name;
list_name.concat(name);
this.setState({
list,
list_name,
details: res.data.details,
name: res.data.name
})
console.log("res data", res)
//console.log("Data is", res.data.name) //displays name in the console
})
.catch(error => console.log('ERROR message'))
}