我有一個簡單的 React 應用程式,我在其中嘗試使用用戶將在輸入中提供的引數向 api 發送請求。我的問題是,只有在第二次單擊按鈕后它才會回傳資料,第一次單擊回傳未定義。
反應查詢鉤子 -
import { useQuery } from "react-query";
import axios from 'axios';
const fetchFilteredsBooks = async (searchText: string) => {
const res = await axios.get(`http://localhost:3001/api/book?search=${searchText}`);
return res.data
}
export const useGetFilteredBooks = (searchText: string) => {
return useQuery('filteredBooks', () => fetchFilteredsBooks(searchText), {
enabled: false
})
}
import styled from "styled-components"
import React, { useState } from "react"
import { useGetFilteredBooks } from "../../hooks/useGetFilteredBooks"
export const SearchBook = () => {
const [text, setText] = useState('')
const { data, refetch } = useGetFilteredBooks(text);
const handleOnChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setText(event.target.value)
}
const handleOnSubmit = (e: any) => {
e.preventDefault();
console.log(text);
refetch();
console.log(data);
}
return (
<form onSubmit={handleOnSubmit}>
<Input value={text} onChange={handleOnChange} placeholder="Enter the name of the book or author" />
<button type="submit">Show</button>
</form>
)
}
const Input = styled.input`
padding: 10px 10px;
width: 300px;
`
uj5u.com熱心網友回復:
因為console.log(data)您呼叫 inside handleOnSumbit,所以將其移至外部:
import styled from "styled-components"
import React, { useState } from "react"
import { useGetFilteredBooks } from "../../hooks/useGetFilteredBooks"
export const SearchBook = () => {
const [text, setText] = useState('')
const { data, refetch } = useGetFilteredBooks(text);
const handleOnChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setText(event.target.value)
}
const handleOnSubmit = (e: any) => {
e.preventDefault();
console.log(text);
refetch();
}
console.log(data) //<== Move to here
return (
<form onSubmit={handleOnSubmit}>
<Input value={text} onChange={handleOnChange} placeholder="Enter the name of the book or author" />
<button type="submit">Show</button>
</form>
)
}
const Input = styled.input`
padding: 10px 10px;
width: 300px;
`
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/479164.html
標籤:反应
