我一直在尝试学习React钩子,以开始构建个人项目,但遇到了一些障碍。目前,当我发出axios请求时,页面将重置并且没有数据显示。
为了确保它以正确的方式工作,我制作了一个类版本,并且能够检索数据并将其上传到setState状态。
import React, { useState } from "react";
import axios from "axios";
const Form = () => {
const [signup, setForm] = useState({ username: "", email: "", password: "" });
const [user, setUser] = useState({ user: "" });
const submit = () => {
axios.get("/api/users").then(user => {
setUser({ user });
});
};
return (
<div>
{user.username}
<h1>This is the Landing Page!</h1>
<form onSubmit={submit}>
<input
type="text"
placeholder="Enter Username"
value={signup.username}
onChange={e => setForm({ ...signup, username: e.target.value })}
/>
<input
type="text"
placeholder="Enter Email"
value={signup.email}
onChange={e => setForm({ ...signup, email: e.target.value })}
/>
<input
type="password"
placeholder="Enter Your Password"
value={signup.password}
onChange={e => setForm({ ...signup, password: e.target.value })}
/>
<input type="submit" value="Submit" />
</form>
</div>
);
};
class选项有效
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
user: ""
};
}
loadData = () => {
console.log(this.state);
axios.get("/api/users").then(user => {
console.log(user.data);
debugger;
this.setState({ user });
});
};
render() {
return (
<div>
<h1>This is the header</h1>
<button onClick={this.loadData}>This is a button</button>
</div>
);
}
}
我期望数据能够持久存在。它确实出现在console.log中,但即使在几秒钟之内消失,就好像整个页面仍在重新加载一样。当我输入内容时,它可以工作,但不能在axios呼叫上使用。
答案 0 :(得分:1)
将onSubmit函数更改为以下内容,以避免重新加载页面。
const submit = (e) => {
e.preventDefault();
axios.get("/api/users").then(user => {
setUser({ user });
});
};
答案 1 :(得分:0)
您想通过添加event.preventDefault()来禁止浏览器提交表单,并让您的Submit()函数改为使用Axios(或提取)发送该请求:
const submit = event => {
event.preventDefault();
...
}