Skip to main content

客户端抓取

当你的页面不需要 SEO 索引、不需要预渲染数据或页面内容需要频繁更新时,客户端数据获取非常有用。与服务器端渲染 API 不同,你可以在组件级别使用客户端数据获取。

¥Client-side data fetching is useful when your page doesn't require SEO indexing, when you don't need to pre-render your data, or when the content of your pages needs to update frequently. Unlike the server-side rendering APIs, you can use client-side data fetching at the component level.

如果在页面级别完成,则在运行时获取数据,并且页面内容随着数据变化而更新。当在组件级别使用时,在组件挂载时获取数据,并随着数据的变化更新组件的内容。

¥If done at the page level, the data is fetched at runtime, and the content of the page is updated as the data changes. When used at the component level, the data is fetched at the time of the component mount, and the content of the component is updated as the data changes.

请务必注意,使用客户端数据获取可能会影响应用的性能和页面的加载速度。这是因为数据获取是在组件或页面安装时完成的,并且数据没有被缓存。

¥It's important to note that using client-side data fetching can affect the performance of your application and the load speed of your pages. This is because the data fetching is done at the time of the component or pages mount, and the data is not cached.

使用 useEffect 获取客户端数据

¥Client-side data fetching with useEffect

以下示例展示了如何使用 useEffect 钩子在客户端获取数据。

¥The following example shows how you can fetch data on the client side using the useEffect hook.

import { useState, useEffect } from 'react'

function Profile() {
const [data, setData] = useState(null)
const [isLoading, setLoading] = useState(true)

useEffect(() => {
fetch('/api/profile-data')
.then((res) => res.json())
.then((data) => {
setData(data)
setLoading(false)
})
}, [])

if (isLoading) return <p>Loading...</p>
if (!data) return <p>No profile data</p>

return (
<div>
<h1>{data.name}</h1>
<p>{data.bio}</p>
</div>
)
}

使用 SWR 获取客户端数据

¥Client-side data fetching with SWR

Next.js 背后的团队创建了一个名为 SWR 的用于数据获取的 React hook 库。如果你要在客户端获取数据,强烈建议你这样做。它处理缓存、重新验证、焦点跟踪、按时间间隔重新获取等等。

¥The team behind Next.js has created a React hook library for data fetching called SWR. It is highly recommended if you are fetching data on the client-side. It handles caching, revalidation, focus tracking, refetching on intervals, and more.

使用与上面相同的示例,我们现在可以使用 SWR 来获取配置文件数据。SWR 会自动为我们缓存数据,并在数据过时时重新验证数据。

¥Using the same example as above, we can now use SWR to fetch the profile data. SWR will automatically cache the data for us and will revalidate the data if it becomes stale.

有关使用 SWR 的更多信息,请查看 SWR 文档

¥For more information on using SWR, check out the SWR docs.

import useSWR from 'swr'

const fetcher = (...args) => fetch(...args).then((res) => res.json())

function Profile() {
const { data, error } = useSWR('/api/profile-data', fetcher)

if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>

return (
<div>
<h1>{data.name}</h1>
<p>{data.bio}</p>
</div>
)
}