【问题标题】:Receiving status 400 when fetching with React Hook Form使用 React Hook Form 获取时收到状态 400
【发布时间】:2021-07-02 19:54:43
【问题描述】:

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

按照 React Hook Form 文档提供的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>

【问题讨论】:

    标签: reactjs react-hooks react-hook-form


    【解决方案1】:

    您的 query 状态永远不会更新,您甚至没有为 useState 返回的 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}`);
      // ...
    };
    

    【讨论】:

    • 感谢您的回复。我现在可以搜索,但我收到了错误的回复。当我获取${data.query} 时,我会收到一个标题中带有undefined 的书籍列表。当我获取${query} 时,我会收到一个标题中带有object 的书籍列表。
    • 我建议在响应数据上使用console.log() 来验证它是否与您期望的形状相匹配。如果形状匹配并且数据不正确,则问题可能出在服务器上,您需要进行故障排除。
    • 我想通了!感谢您的指导! const result = await axios.get(${API_BASE_URL}?q=${data.book});
    • 啊,有道理,我没注意到查询输入的name是“书”。
    猜你喜欢
    • 1970-01-01
    • 2021-05-09
    • 2021-10-21
    • 2020-11-15
    • 2021-03-22
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    相关资源
    最近更新 更多