Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Next.js通过服务器端渲染对查询进行响应_Javascript_Reactjs_Next.js_Server Side Rendering_React Query - Fatal编程技术网

Javascript 使用Next.js通过服务器端渲染对查询进行响应

Javascript 使用Next.js通过服务器端渲染对查询进行响应,javascript,reactjs,next.js,server-side-rendering,react-query,Javascript,Reactjs,Next.js,Server Side Rendering,React Query,我正在尝试使用react query和nextjs在服务器上预取查询。它适用于获取项目列表的初始查询。然而,当我试图获取组件中的每个项时,它只在客户端获取它 导出默认函数Home(){ const{data}=useQuery(“pokemons”,fetchPokemons); 返回( {data.map((口袋妖怪)=>( ))} ); } 导出异步函数getStaticProps(){ const queryClient=new queryClient() 等待queryClient.pr

我正在尝试使用react query和nextjs在服务器上预取查询。它适用于获取项目列表的初始查询。然而,当我试图获取组件中的每个项时,它只在客户端获取它

导出默认函数Home(){
const{data}=useQuery(“pokemons”,fetchPokemons);
返回(
{data.map((口袋妖怪)=>(
))}
);
}
导出异步函数getStaticProps(){
const queryClient=new queryClient()
等待queryClient.prefetchQuery('pokemons',fetchPokemons)
const fetchedPokemons=queryClient.getQueryData()
//查询每个口袋妖怪
fetchedPokemons.forEach(异步(pokemon)=>{
等待queryClient.prefetchQuery(pokemon.name,()=>fetchPokemon(pokemon.url))
});
返回{
道具:{
脱水状态:脱水(queryClient),
},
}
}
下面是组件的代码,它也查询每个项目

const口袋妖怪=({Pokemon})=>{
const{data}=useQuery(pokemon.name,()=>fetchPokemon(pokemon.url))
//仅在浏览器中记录,在服务器上未定义
{console.log(数据)}
返回(
名称-{data.Name}
基本XP-{data.Base\u experience}
)
}

您能告诉我,我做错了什么,查询没有在服务器上执行,或者是库本身的问题吗?

我能够通过将两个抓取函数合并为一个这样的函数来解决这个问题

const fetchPokemons=async()=>{
const{data}=wait axios.get(
"https://pokeapi.co/api/v2/pokemon?limit=10&offset=0"
);
const pokemonaray=等待承诺(
data.results.map(异步(口袋妖怪)=>{
const res=wait axios.get(pokemon.url);
返回res.data;
})
);
返回口袋妖怪;
};
导出默认函数Home(){
const{data}=useQuery(“pokemons”,fetchPokemons);
返回(
{data.map((口袋妖怪)=>(
))}
);
}
导出异步函数getStaticProps(){
const queryClient=new queryClient();
等待queryClient.prefetchQuery(“口袋妖怪”,fetchPokemons);
返回{
道具:{
脱水状态:脱水(queryClient),
},
};
}

使用
getQueryData
从缓存中获取数据时,需要提供要获取的数据的
键:

await queryClient.prefetchQuery('pokemons', fetchPokemons)
const fetchedPokemons = queryClient.getQueryData('pokemons')
或者,也可以使用立即检索数据

try {
  const fetchedPokemons = await queryClient.fetchQuery('pokemons')
} catch (error) {
  // handle error
}
请注意,
fetchQuery
会抛出错误(与
prefetchQuery
相反,后者不会),因此您可能希望以某种方式处理错误。

返回“props:detercheedstate”的原因是什么,因为我没有看到您在Home组件中使用它?