我有以下组件:
import React, { Component } from 'react';
import axios from 'axios';
class Form extends Component {
constructor(props) {
super(props);
this.state = {
firstName: '',
email: '',
university: '',
degree: ''
}
this.setFirstName = this.setFirstName.bind(this);
this.setEmail = this.setEmail.bind(this);
this.setUniversity = this.setUniversity.bind(this);
this.setDegree = this.setDegree.bind(this);
}
setFirstName(name) {
this.setState({
firstName: name
});
}
setEmail(email) {
this.setState({
email: email
});
}
setUniversity(university) {
this.setState({
university: university
});
}
setDegree(degree) {
this.setState({
degree: degree
});
}
getSingleInputValue(e) {
if(e.target.getAttribute('name') == 'name'){
this.setFirstName(e.target.value);
}
if(e.target.getAttribute('name') == 'email'){
this.setEmail(e.target.value);
}
if(e.target.getAttribute('name') == 'university'){
this.setUniversity(e.target.value);
}
if(e.target.getAttribute('name') == 'degree'){
this.setDegree(e.target.value);
}
}
submitForm(e) {
var token = document.getElementsByTagName("meta")[0].getAttribute("content");
e.preventDefault();
axios({
url: '/save-data',
method: 'POST',
contentType: 'application/json',
data: {
"candidates": [
{
"name": this.state.firstName,
"email": this.state.email,
"university": this.state.university,
"degree": this.state.degree
}
]
},
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': token
}
}).then(function(response) {
console.log(response);
// go to next screen
})
}
render() {
let isVisible = this.props.visibility ? "" : "hide-form";
return(
<form className={"form " + isVisible}>
<input
placeholder="John Green"
type="text"
name="name"
onChange={this.getSingleInputValue.bind(this)} />
<input
placeholder="Email"
type="text"
name="email"
onChange={this.getSingleInputValue.bind(this)} />
<input
placeholder="University"
type="text"
name="university"
onChange={this.getSingleInputValue.bind(this)} />
<input
placeholder="Degree"
type="text"
name="degree"
onChange={this.getSingleInputValue.bind(this)} />
<button onClick={this.submitForm.bind(this)}>enter</button>
</form>
);
}
}
export default Form;
是否有一种方法可以将从表单中捕获的队列中的数据保存到以后(一旦连接重新进入)与AXIOS一起发送?
答案 0 :(得分:1)
听起来像localStorage的用例。您的提交处理程序,而不是将数据发布到服务器,可以将其保存到本地浏览器存储中,该存储具有用于以键/值模式保存和获取数据的API(请参阅上面的链接)。
您可以将JSON序列化几乎任何普通的Javascript数据并将其保存在localStorage中,然后在您确定时间时,汇总数据并通过网络发送。
像 -
// ...
submitForm(e) {
e.preventDefault();
window.localStorage.setItem("foo", JSON.stringify({
name: this.state.firstName,
email: this.state.email,
university: this.state.university,
degree: this.state.degree
});
}
当然会有更多细节要解决,但那将是一般的要点。