我正在构建我的第一个 Custom React Hook,并且对我认为代码的一个简单方面感到困惑:
export const useFetch = (url, options) => {
const [data, setData] = useState();
const [loading, setLoading] = useState(true);
const { app } = useContext(AppContext);
console.log('** Inside useFetch: options = ', options);
useEffect(() => {
console.log('**** Inside useEffect: options = ', options);
const fetchData = async function() {
try {
setLoading(true);
const response = await axios.get(url, options);
if (response.status === 200) {
setData(response.data);
}
} catch (error) {
throw error;
} finally {
setLoading(false);
}
};
fetchData();
}, []);
return { loading, data };
};
我传递给useFetch
两个参数:一个 url 和一个headers
包含 AWS Cognito 授权密钥的对象,如下所示:(Authorization: eyJraWQiOiJVNW...
为简洁起见)
当我这样做时,options
对象确实存在于内部附近useFetch
但在useEffect
构造内部它是空的。然而,url
字符串在两种情况下都正确填充。
这对我来说毫无意义。可能有人知道为什么会这样吗?