我撰寫了一個簡單的表單,它將帶有資料的發布請求發送到服務器。單擊提交按鈕時,我想清除表單,因此我創建了一個重繪 頁面的函式。該功能正常作業,但現在資料沒有發送到服務器。
import React, {Component} from "react";
import axios from "axios";
class PostForm extends Component {
constructor(props) {
super(props);
this.state = {
id: '',
name: '',
surname: '',
country: ''
}
}
changeHandler = e => {
this.setState({[e.target.name]: e.target.value});
}
clearFunc = () => {
window.location.reload(false);
}
submitHandler = e => {
e.preventDefault();
console.log(this.state);
axios.post('http://localhost:8080/human/add/', this.state)
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
});
}
render() {
const {id, name, surname, country} = this.state;
return (
<div>
<form id="input-form" onSubmit={() => {
this.submitHandler();
this.clearFunc()
}}>
<div>
<input type="number" name="id" value={id} onChange={this.changeHandler}/>
</div>
<div>
<input type="text" name="name" value={name} onChange={this.changeHandler}/>
</div>
<div>
<input type="text" name="surname" value={surname} onChange={this.changeHandler}/>
</div>
<div>
<input type="text" name="country" value={country} onChange={this.changeHandler}/>
</div>
<button type="submit">Submit</button>
</form>
</div>
)
}
}
export default PostForm;
uj5u.com熱心網友回復:
我會把這條線移到那個塊this.clearFunc()里面,像這樣:submitHandlerthen
submitHandler = (e) => {
e.preventDefault();
console.log(this.state);
axios
.post("http://localhost:8080/human/add/", this.state)
.then((response) => {
console.log(response);
this.clearFunc();
})
.catch((error) => {
console.log(error);
});
};
另外,如果只是清空表單,不需要重繪 頁面,你可以這樣做:
clearFunc = () => {
this.setState({
id: "",
name: "",
surname: "",
country: "",
});
};
uj5u.com熱心網友回復:
看起來你是在錯誤的流程中做的。如果要在提交后清除表單,主要是在 React App 中,只需在 POST 成功后將所有狀態設定為空字串(這意味著我們將其放入 then() 中)。
它看起來像這樣:
clearForm = () => {
// use this to reset the states
this.setState({
id: '',
name: '',
surname: '',
country: ''
})
}
submitHandler = e => {
e.preventDefault();
console.log(this.state);
axios.post('http://localhost:8080/human/add/', this.state)
.then(response => {
console.log(response)
clearForm() // <-- call the function here
})
.catch(error => {
console.log(error)
});
}
為什么不應該將 clearForm() 放在表單 onSubmit 中?因為我們永遠不知道 POST 請求會成功與否。保留值是一個好主意,因為 POST 請求有錯誤回應。
uj5u.com熱心網友回復:
我認為您不需要重繪 頁面,只要您使用的是e.preventDefault()您正在停止通過表單重繪 頁面的默認行為。
如果您只想清空表單,那么您可以使用document.form.reset()where 表單是您分配給表單的名稱。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492531.html
標籤:javascript html 反应
下一篇:實時資料庫云功能在完成前回傳結果
