我正在尝试发出可重用的
GET
和 POST
请求,但在可重用的获取请求组件中设置 Invalid hook call
状态时出现错误 data
。我刚刚了解到我们只能在 React 组件中使用钩子,那么如何才能使该功能可重用呢?
import axios from "axios";
import { useContext, useEffect, useState } from "react";
import AuthContext from "../../context/Auth-context/AuthContext";
import { useNavigate } from "react-router-dom";
export const POST = (url, body, credentials) => {
const [data, setData] = useState([]);
const [isLoaded, setIsLoaded] = useState(false);
const [error, setError] = useState(null);
const { dispatch } = useContext(AuthContext);
const navigate = useNavigate();
useEffect(() => {
const fetchData = () => {
axios
.post(url, body, { withCredentials: credentials })
.then((response) => {
setIsLoaded(true);
setData(response.data);
})
.catch((error) => {
if (error.status === 401) {
dispatch({ type: "LOGOUT" });
navigate("/login");
return;
}
setError(error);
});
};
fetchData();
}, [url, credentials, dispatch, navigate, body]);
return { error, isLoaded, data };
};
const approve = async (id) => {
const { data, error, isLoaded } = POST(
"http://localhost:8000/api/new-users",
id,
true
);
if (error) {
return (
<Error/>
);
}
if (!isLoaded) {
return (
<Loader/>
);
}
console.log(data);
};
将
POST
重命名为“usePost”并检查。
您必须遵循以下命名约定: React 组件名称必须以大写字母开头,例如 StatusBar 和 SaveButton。 React 组件还需要返回 React 知道如何显示的东西,比如一段 JSX。 挂钩名称必须以 use 开头,后跟大写字母,例如 useState (内置)或 useOnlineStatus (自定义,如页面前面的内容)。钩子可能返回任意值。
https://react.dev/learn/reusing-logic-with-custom-hooks#hook-names-always-start-with-use