【问题标题】:Empty response from API with React来自 API 的空响应与 React
【发布时间】:2021-03-24 16:57:41
【问题描述】:

我正在使用 Google 图书 API 来获取数据。当我单击按钮以获取数据时,响应是一个空数组。我不知道我在使用异步函数时做错了什么。

export default function SearchInput() {
  const [inputSearch, setInput] = useState("")
  const [bookSearch, setBookSearch] = useState([])

  //async function to retrieve data from an API
  const fetchBooks = async() => {
    const res = await fetch(
      `https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes&key=${apikey}`
    );
    const data = await res.json();
    setBookSearch(bookSearch);
    console.log(bookSearch); //shows an empty array
  }

  //search function
  const handleSearch = (e) => {
    e.preventDefault();
    fetchBooks();
  }    

  return (
    <div>
      <h2>search book</h2>
      <p>libro: {inputSearch}</p>
      <form onSubmit={handleSearch}> // this trigger the search function
        <input placeholder="Title, Author" 
          type="text"
          value={inputSearch}
          onChange={e=>{setInput(e.target.value)}}/>
        <button type="submit">Search</button>
      </form>
    </div>
  );
}

【问题讨论】:

  • 因为你告诉它:const [bookSearch, setBookSearch] =useState([]) 所以bookSearch 开始是一个空数组,你永远不会改变值。

标签: javascript reactjs async-await react-hooks use-state


【解决方案1】:

在您的fetchBooks() 中,您每次都通过调用setBookSearch(bookSearch)bookSearch 状态设置为它自己的值。由于bookSearch的值默认为空数组,所以每次都是空数组。确保使用获取的 data 更新状态:

const fetchBooks = async () => {
  const res = await fetch(URL);
  const data = await res.json();
  setBookSearch(data);
  console.log(bookSearch); // it's not yet set!
};

您还尝试在“更新”状态后立即记录状态。不要忘记useState 是异步的,就像类组件中的setState 一样。您不能在一行更新状态并假设它已经在下一行更改。您可能会记录未更改的状态。如果您想在更改后记录新值,可以使用 useEffect 挂钩。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2023-03-12
    • 1970-01-01
    • 2018-05-12
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多