新手 | React 获取数据的基本方法

681 阅读1分钟

React 中,我们可以使用多种方式从服务器获取数据。

下面介绍几种常用的方式以及如何使用。

Fetch 方法

fetch() 方法用于向服务器发送请求并在网页中加载信息。请求可以是任何返回 JSON 或 XMLDocument 格式数据的 API。该方法返回一个 Promise 对象。

function App() {
    useEffect(() => {
        fetch('https://demo.com/')
        .then(response => response.json())
        .then(json => console.log(json))
    }, []);

    return(
        <div> Fetch method used for fetching the data</div>
    );

}

Async-Await

使用 async-await 获取数据的方式,因为它使我们可以省略 .then() ,这种同步的方式使代码条例更清晰明了。

对于 async 包裹的函数,我们可以使用 await 函数等待 Promise

function App() {
    useEffect(() =>{
        (async () => {
            try {
                const result = await.axiox.get('https://demo.com/')
                console.log(result.data)
            } catch (error){
                console.error(error)
            }
        })()
    })
    return <div> Async-Await method used for fetch the data</div>
}

Axios 库

使用 Axios,我们可以轻松地向 REST API 发送异步 HTTP 请求并执行创建、读取、更新和删除操作。Axios 可以按照需要在纯 JavaScript 或任何库中导入。

function App(){
     useEffect(() => {
        axiox.get('https://demo.com/')
        .then((response) => console.log(response.data));
     }, [])
     return(
        <div> Axios library used for fetch the data</div>
     )
}

自定义 Hook

自定义 Hook 实际上是一个 React 组件,其名称将以 use 开头,例如 useFetch。可以在多个组件中使用它。

const useFetch =(url) => {

    const [isLoading, setIsLoading] = useState(false)
    const [apiData, setApiData] = useState(null)
    const [ serverError, setServerError] = useState(null)

    useEffect(() => {
        setIsLoading(true)
        const fetchData = async () => {
            try {
                const resp = await.axiox.get(url)
                const data = await resp? data
                setApiData(data)
                setIsLoading(false)
            } catch(error){
                setServerError(error)
                setIsLoading(false)
            }
        }
        fetchData()
    }, [url])
    return { isLoading, apiData, serverError}

}

使用该组件的方式如下:导入 useFetch hook,并传递要从中获取数据的 API 端点的 URL。然后,与其他任何 React hook API一样,我们可以直接使用它来获取数据。

import useFetch from './useFetch';

const App = () {
    const {isLoading, serverError, apiData} = useFetch('https://demo.com')

    return(
        <div>
            <h2>Api Data</h2>
            { isLoading && <span>Loading......</span>}
            {isLoading  && serverError ? (
                <span>Error in fetching data...</span>
            ) : (
                <span>{JSON.stringify{apiData}}</span>
            )}
        </div

Request Query库

Request Query库不仅仅支持数据获取,还提供了缓存和重新获取的支持,这对于防止不规则性并确保我们的应用程序感觉更快速的整体用户体验产生影响。

import axios from "axios";
import {useQuery}  from 'react-query'

function App() {
    const { isLoading, error, data} = useQuery('posts', () => axios('https://demo.com'))
    console.log(data)
    return <div> Request Query库用于获取数据</div>
}