Mir*_*ung 3 reactjs react-hooks
我需要向许多端点发送GET和POST请求。
例如,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 fetch('/weather', ...
}
Run Code Online (Sandbox Code Playgroud)
我读过useAsync一次关于肯特的钩子,我认为你的第二种方法很适合。以下是使用useAsyncstar-wars API 示例制作可重用钩子的完整代码:-
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 Code Online (Sandbox Code Playgroud)
我喜欢的部分是返回run函数,我们可以将 any承诺传递到其中,其余部分由钩子管理。它使 API 的用户可以更好地控制要执行的内容。
这是一个有效的代码和框:-
| 归档时间: |
|
| 查看次数: |
621 次 |
| 最近记录: |