gpt4 book ai didi

reactjs - 在函数 react 钩子(Hook)中访问函数参数

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

我正在编写一个自定义 react 钩子(Hook),用于从端点获取数据。这是函数的样子

import { useState } from "react";

const useHttp = async (endpoint, method, data) => {

const [loading, setLoading] = useState(false)
const [fetchedData, setfetchedData] = useState(null)

setfetchedData(await fetch.method(endpoint));
return [isLoading, fetchedData]
}

export default useHttp;
如您所见,我想对传递给 useHttp 钩子(Hook)的任何方法执行获取请求。请有人指出我该怎么做?

最佳答案

你不能将异步函数传递给 React Hooks。您必须 useEffect

import { useState, useEffect } from "react";

const useHttp = (endpoint, method, options) => {
const [isLoading, setLoading] = useState(false);
const [fetchedData, setFetchedData] = useState(null);

useEffect(() => {
setLoading(true);

fetch(endpoint, { method, ...options })
.then(data => data.json())
.then((json) => {
// do something with JSON data
setFetchedData(json);
})
.catch((err) => {
// do something with err
})
.finally(() => {
setLoading(false);
});
}, []);
return [isLoading, fetchedData];
};

export default useHttp;

关于reactjs - 在函数 react 钩子(Hook)中访问函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62553777/

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