我的 Google Books 克隆应用程序让用户提交他们输入的查询,然后显示响应数据。
按照React Hook Form 文档提供的模式验证示例,我收到Error: Request failed with status code 400
. 我究竟做错了什么?
const [query, setQuery] = useState("");
const [books, setBooks] = useState({ items: [] });
const {
register,
handleSubmit,
formState: { errors }
} = useForm({
resolver: yupResolver(schema)
});
const handleBookFetch = async () => {
try {
const result = await axios.get(`${API_BASE_URL}?q=${query}`);
setBooks(result.data);
} catch (error) {
console.log(error);
}
};
<form onSubmit={handleSubmit(handleBookFetch)}>
<label name="book">
Search the world's most comprehensive index of full-text books.
</label>
<div>
<input type="text" name="book" {...register("book")} onChange={(event) => setQuery(event.target.value)} />
<p>{errors.book?.message}</p>
<button type="submit">Search</button>
</div>
</form>
您的query
状态永远不会更新,您甚至没有为setQuery
useState 返回的函数分配名称。因此,query
将始终具有其默认值“”。您的服务器可能会返回 400 Bad Request,因为您向它发送了一个空查询字符串。
我认为 React Hook Form 将您的数据作为对象传递给您的 handleSubmit 函数,因此您可以从中获取查询的当前值:
const handleBookFetch = async (data) => {
// ...
// "book" is the name of the input element
const result = await axios.get(`${API_BASE_URL}?q=${data.book}`);
// ...
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句