[英]Why does this custom hook return indefined in react?
i am creating a custom hook in React, this is my code:我正在 React 中创建一个自定义钩子,这是我的代码:
import {useEffect} from 'react';
const useFetch = (url) => {
useEffect(() => {
const fetchData = () => {
const data = url + "TEST";
return data;
}
fetchData();
})
}
export default useFetch;
It now returns some dummy value but that is just because of testing purposes.它现在返回一些虚拟值,但这只是出于测试目的。
Here is where i invoke my custom hook:这是我调用自定义钩子的地方:
const Data = useFetch("https://customapiurlrandom.com/");
useEffect(() => {
console.log(Data);
}, [])
The thing is, when i check my console i see undefined
.问题是,当我检查我的控制台时,我看到了
undefined
。 And i can't find out why.我不知道为什么。
Any ideas?有任何想法吗? Thanks in advance.
提前致谢。
Your custom hook didn't return anything.您的自定义挂钩没有返回任何内容。 You should add a state to keep the value and return it
您应该添加一个 state 以保留该值并返回它
import {useEffect, useState} from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = () => {
const data = url + "TEST";
return data;
}
setData(fetchData());
},[url, setData]);
return data;
}
export default useFetch;
And then use like this然后像这样使用
const Data = useFetch("https://customapiurlrandom.com/");
useEffect(() => {
console.log(Data);
}, [Data])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.