我正在使用Next.js为我的投资组合建立一个项目.而且,我正在try 使用Tanstack query和Axios来处理API.问题是,我在try 获取数据时遇到错误.数据是从API中获取的,当我在函数内部console.log
时可以看到它,但当我试图在函数外访问它时,它返回undefined
.
下面是我的函数代码:
const Home = () => {
const {data} = useQuery({
queryKey: ['products'],
queryFn: async () => {
const res = await axios.get(
'https://fakestoreapi.com/products'
)
const data = await res.data
console.log(data)
//can access data here
}
})
console.log(data)
//cannot access data here and returns undefined.
return (
<section>
//some codes here
</section>
)
}
我在控制台中也收到此错误:
查询数据不能未定义.请确保返回值 而不是您的查询函数中未定义的.受影响的查询关键字: ["产品"]
我到处寻找修复程序,但没有找到任何导致这一问题的线索.有人能帮我解决这个问题吗?