小编Mir*_*ung的帖子

如果我需要向多个端点发送请求,我应该如何制作自定义反应钩子?

我需要向许多端点发送GETPOST请求。

例如,GET | POST水果清单、GET | POST天气清单...

不是在一页上,它们是分开的(浏览器路由)。例如)水果页面,天气页面...

我想知道如何在这种情况下制作自定义反应钩子。

我搜索了很多,但所有的写作都是基于一个单一的 api 端点。


方式一

创建一个可重用的 fetch 函数。

function useGetFetch(url){
    const response = await fetch(url, ...
    return response.json()
}

function usePostFetch(url){
    const response = await fetch(url, ...
    return response.json()
}
Run Code Online (Sandbox Code Playgroud)

方式二

为每个创建一个函数。

function getFruitList(){
    const response = await fetch('/fruit', ...
}

function postFruitList(){
    const response = await fetch('/fruit', ...
}

function getWeatherList(){
    const response = await fetch('/weather', ...
}

function postWeatherList(){
    const response = await …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

3
推荐指数
1
解决办法
621
查看次数

标签 统计

react-hooks ×1

reactjs ×1