R

React Hooks 数据处理第一部分 - 获取数据

2025-06-08

React Hooks 数据处理第一部分 - 获取数据

所以,React Hooks 的炒作已经结束,社区也不再过多地讨论它们了。但说真的,Hooks 真的非常强大。在这篇文章中,我将解释如何使用 React Hooks 获取数据并提交给任何 API(本指南中我将使用 REST)。

编写自己的钩子

我们将从编写第一个钩子函数开始,该钩子函数用于通过 API 获取书籍。示例代码如下:

import { useEffect, useState } from 'react'

// The hook is just a simple function which we can export
export const useFetchBooks = () => {

  // First we define the necessary states for our hook
  // this includes book, the loading state and potential errors
  const [books, setBooks] = useState([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)

  // useEffect can be compared to componentDidMount,
  // componentDidUpdate and componentDidUnmount
  // read more about useEffect here:
  // https://reactjs.org/docs/hooks-effect.html
  useEffect(() => {

    // First we set the loading and error states
    setLoading(true)
    setError(null)

    fetch('https://library.com/api/books')
      .then(res => res.json())
      .then(json => {
        setLoading(false)
        if (json.books) {
          setBooks(json.books)
        } else {
          setBooks([])
        }
      })
      .catch(err => {
        setError(err)
        setLoading(false)
      })
  }, [])
  return { books, loading, error }
}

Enter fullscreen mode Exit fullscreen mode

这看起来很复杂,但实际上并不复杂。删除注释后,它将是一个非常简短的函数,用于获取数据并更新状态。

现在我们有了钩子,我们可以在这样的组件中使用它:

import React from 'react'
import { useFetchBooks } from './utils/hooks'

const BookList = () => {
  // use your own hook to load the data you need
  const { books, loading, error } = useFetchBooks()

  if (loading) return <div>Loading...</div>
  if (error) return <div>{error}</div>

  return (
    <div>
      { 
        books &&
        books.length > 0 &&
        books.map(book => <div key={book.id}>{book.title}</div>)
      } 
    </div>
  )
}

export default BookList
Enter fullscreen mode Exit fullscreen mode

在钩子中使用参数

现在我们的钩子已经正常工作了,但还是有点笨。假设你希望用户能够在列表中搜索书籍。你可以这样做:

import { useEffect, useState } from 'react'

// Note here the new parameter we pass into the hook called "search"
// this will be used to search the api for specific books
export const useFetchBooks = (search) => {
  const [books, setBooks] = useState([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)

  useEffect(() => {
    setLoading(true)
    setError(null)

    // Change the apiUrl according to the search string
    const apiUrl = search && search.length > 0 ?
      `https://library.com/api/books?search=${search}` :
      'https://library.com/api/books'

    fetch(apiUrl)
      .then(res => res.json())
      .then(json => {
        setLoading(false)
        if (json.books) {
          setBooks(json.books)
        } else {
          setBooks([])
        }
      })
      .catch(err => {
        setError(err)
        setLoading(false)
      })

  // This is important. We pass the new search parameter into
  // the empty array we had before. This means, the effect
  // will run again if this parameter changes
  }, [search])

  return { books, loading, error }
}

Enter fullscreen mode Exit fullscreen mode

现在您可以在组件中像这样使用钩子:

const { books, loading, error } = useFetchBooks(props.search)
Enter fullscreen mode Exit fullscreen mode

这对于第 1 部分来说应该足够了,并且应该阐明如何使用钩子从任何 API 获取数据。

一旦我完成,我将更新此帖子并添加第 2 部分的链接。

玩得开心!

鏂囩珷鏉ユ簮锛�https://dev.to/bd​​bchgg/react-hooks-for-data-part-1-fetching-data-28ge
PREV
在 Node.js 中构建您自己的 Dev.to API 客户端
NEXT
Ubuntu 20.04 鼠标滚轮速度 Ubuntu 20.04 鼠标滚轮速度