在同一个组件中调用自定义钩子两次



我想使用这个自定义钩子来发出api请求:

export default function useFetch({ method, url, data = null, config = null }) {
const [response, setResponse] = useState(null);
const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
api[method](url, JSON.parse(config), JSON.parse(data))
.then((res) => {
setResponse(res.data);
})
.finally(() => {
setIsLoading(false);
});
} catch (err) {
setError(err);
}
};
fetchData();
}, [api, method, url, data, config]);
return { response, error, isLoading };
}

上面的代码并不重要。所以不要太在意它。我的问题是如何在同一个组件内进行两个api调用。这可能吗?

export const programApi = axios.create({
baseURL: programApiUrl,
});
const {response, isLoading} = useFetch({
api: programApi,
method: "get",
url: "/SportsProgram/active_sport_type",
config: JSON.stringify({ requireAuthentication: true }),
});
useEffect(() => {
if (response !== null) {
// do more stuff if you wish
}
}, [response]);

是否可能使用两次useFetch?

在组件中销毁对象时,可以重命名对象中的值,如下所示:

const {response, isLoading} = useFetch({
api: programApi,
method: "get",
url: "/SportsProgram/active_sport_type",
config: JSON.stringify({ requireAuthentication: true }),
});
const {response: response2, isLoading: isLoading2} = useFetch({
api: programApi,
method: "get",
url: "/SportsProgram/active_sport_type",
config: JSON.stringify({ requireAuthentication: true }),
});
console.log(response, response2)

或者不是在钩子中返回一个对象,而是返回一个数组。然后在你的组件中,你可以销毁它们,并给它们取不同的名字。

export default function useFetch({ method, url, data = null, config = null }) {
const [response, setResponse] = useState(null);
const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
api[method](url, JSON.parse(config), JSON.parse(data))
.then((res) => {
setResponse(res.data);
})
.finally(() => {
setIsLoading(false);
});
} catch (err) {
setError(err);
}
};
fetchData();
}, [api, method, url, data, config]);
return [ response, error, isLoading ];
}

然后在你的组件中你可以这样做:

const [firstResponse, firstError, firstIsLoading] = useFetch(...your stuff)
const [secondResponse, secondError, secondIsLoading] = useFetch(...your stuff)