我对React很陌生,我已经在后端(Express)上创建了CRUD,我想将其绑定到React前端。我有一个允许添加用户的表单,我希望在成功添加用户后更新状态。我通过实现“ document.createElement”并在5秒钟后(使用setTimeout)刷新页面来使其得以启动并运行。我在想,一旦POST成功,如何使组件重新呈现(更新状态)。
到目前为止,这是我所管理的:
class App extends Component {
constructor() {
super();
this.state = {
users: null
};
}
componentDidMount() {
axios
.get("http://localhost:3000/customer_all")
.then(res => {
console.log(res);
this.setState({ users: res.data });
})
.then(() => console.log(this.state.users.map(item => item.name)))
.catch(err => console.log(err));
}
submit(e) {
e.preventDefault();
var form = document.forms[0];
var data = {};
var para = document.createElement("p");
para.textContent = "Success";
var id = document.getElementById("message");
data.name = form.name.value;
data.email = form.email.value;
axios
.post("http://localhost:3000/customer", {
name: data.name,
email: data.email,
headers: {
"Content-Type": "application/json"
}
})
.then(response => {
id.appendChild(para);
setTimeout(() => window.location.reload(), 5000);
form.reset();
})
.catch(err => console.log(err));
}
render() {
return (
<div>
<div id="message" />
<form method="POST" onSubmit={this.submit}>
<label htmlFor="name">Nume </label>
<input type="text" name="name" /> <br />
<br />
<label htmlFor="email">Email </label>
<input type="email" name="email" required />
<input type="submit" value="Adauga" />
</form>
<ol>
{!this.state.users
? "loading"
: this.state.users.map((item, i) => <li key={i}>{item.name}</li>)}
</ol>
</div>
);
}
}
预先感谢您的任何提示!
最佳答案
在Submit方法中,将新用户添加到数组和setState中。
submit = (e) => {
e.preventDefault();
var form = document.forms[0];
var data = {};
var para = document.createElement("p");
para.textContent = "Success";
var id = document.getElementById("message");
data.name = form.name.value;
data.email = form.email.value;
axios
.post("http://localhost:3000/customer", {
name: data.name,
email: data.email,
headers: {
"Content-Type": "application/json"
}
})
.then(response => {
const {users} = this.state;
users.push(response.data);
id.appendChild(para);
this.setState({users});
form.reset();
})
.catch(err => console.log(err));
}