使用 React Hook Form 获取时接收状态 400

Receiving status 400 when fetching with React Hook Form

我的 Google 图书克隆应用程序让用户提交他们输入的查询,然后显示响应数据。

根据 React Hook 表单文档提供的 schema validation example,我收到了 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 状态永远不会更新,您甚至没有为使用状态 returns 的 setQuery 函数分配名称。因此,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}`);
  // ...
};