gpt4 book ai didi

reactjs - 如果我需要向多个端点发送请求,我应该如何制作自定义 react 钩子(Hook)?

转载 作者:行者123 更新时间:2023-12-04 12:09:06 25 4
gpt4 key购买 nike

我需要发送GETPOST对许多端点的请求。
例如,GET | POST水果 list ,GET | POST天气列表...
不是在一页上,它们是分开的(浏览器路由)。
例如)水果页面,天气页面...
我想知道如何在这种情况下制作自定义 react 钩子(Hook)。
我搜索了很多,但所有的写作都是基于一个单一的 api 端点。

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

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

function usePostFetch(url){
const response = await fetch(url, ...
return response.json()
}
方式二
为每个创建一个函数。
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 fetch('/weather', ...
}

最佳答案

read关于肯特 useAsync钩一次,我认为你的第二种方法很适合。这是制作可重用的完整代码 useAsync与星球大战 API 示例 Hook :-

import "./styles.css";
import React, { useEffect } from "react";
export default function App() {
const {
run: starShipExec,
status: starshipStatus,
data: starshipData,
error: startshipError
} = useAsync({ status: "idle" });
const {
run: peopleExec,
status: peopleStatus,
data: peopleData,
error: peopleError
} = useAsync({ status: "idle" });

useEffect(() => {
starShipExec(getStarships());
peopleExec(getPeople());
}, [starShipExec, peopleExec]);

return (
<div className="App">
Startships
<ul>
{starshipData?.results.map((res) => (
<li>{res.name}</li>
))}
</ul>
People
<ul>
{peopleData?.results.map((res) => (
<li>{res.name}</li>
))}
</ul>
</div>
);
}

async function getStarships() {
return await fetch("https://swapi.dev/api/starships");
}

async function getPeople() {
return await fetch("https://swapi.dev/api/people");
}

function asyncReducer(_state, action) {
switch (action.type) {
case "pending": {
return { status: "pending", data: null, error: null };
}
case "resolved": {
return { status: "resolved", data: action.data, error: null };
}
case "rejected": {
return { status: "rejected", data: null, error: action.error };
}
default: {
throw new Error(`Unhandled action type: ${action.type}`);
}
}
}

function useSafeDispatch(dispatch) {
const mountedRef = React.useRef(false);
React.useLayoutEffect(() => {
mountedRef.current = true;
return () => (mountedRef.current = false);
}, []);

const safeDispatch = React.useCallback(
(...args) => {
mountedRef.current && dispatch(...args);
},
[dispatch]
);
return safeDispatch;
}

function useAsync({ status }) {
const [state, unsafeDispatch] = React.useReducer(asyncReducer, {
status: status,
data: null,
error: null
});
const dispatch = useSafeDispatch(unsafeDispatch);

const run = React.useCallback(
(promise) => {
if (!promise) {
return;
}
dispatch({ type: "pending" });
promise
.then((data) => data.json())
.then((data) => {
dispatch({ type: "resolved", data });
})
.catch((error) => {
dispatch({ type: "rejected", error });
});
},
[dispatch]
);

return { ...state, run };
}

我喜欢的部分是返回 run我们可以将任何 传入的函数 promise 其余的钩子(Hook)管理。它使 API 的用户可以更好地控制要执行的内容。
这是一个有效的代码和框:-
Edit useAsync-star-wars

关于reactjs - 如果我需要向多个端点发送请求,我应该如何制作自定义 react 钩子(Hook)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68317220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com