1

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

export default function Home() {
  const { data } = useQuery("pokemons", fetchPokemons);
  return (
    <>
      <div>
        {data.map((pokemon) => (
          <Pokemon key={pokemon.name} pokemon={pokemon}/>
        ))}
      </div>
    </>
  );
}

export async function getStaticProps() {
  const queryClient = new QueryClient()
  await queryClient.prefetchQuery('pokemons', fetchPokemons)
  const fetchedPokemons = queryClient.getQueryData()
  //query each pokemon
  fetchedPokemons.forEach(async (pokemon) => {
    await queryClient.prefetchQuery(pokemon.name, () => fetchPokemon(pokemon.url))
  });

  return {
    props: {
      dehydratedState: dehydrate(queryClient),
    },
  }
}

这是也查询每个项目的组件的代码。

const Pokemon = ({pokemon}) => {
  
  const {data} = useQuery(pokemon.name, () => fetchPokemon(pokemon.url))
  // logs only in browser, on server it is undefined
  {console.log(data)}
  return (
    <div>
      <h3>
        Name - {data.name}
        </h3>
        <h4>Base XP - {data.base_experience}</h4>
    </div>
  )
}

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

4

2 回答 2

3

当您使用getQueryData从缓存中获取数据时,您需要提供key您想要获取的数据:

await queryClient.prefetchQuery('pokemons', fetchPokemons)
const fetchedPokemons = queryClient.getQueryData('pokemons')

或者,您也可以使用fetchQuery立即检索数据

try {
  const fetchedPokemons = await queryClient.fetchQuery('pokemons')
} catch (error) {
  // handle error
}

请注意,它fetchQuery会引发错误(而不是prefetchQuery, 不会),因此您可能希望以某种方式处理错误。

于 2021-01-05T10:57:50.937 回答
0

我可以通过将我的两个获取功能组合成一个来解决这个问题

const fetchPokemons = async () => {
  const { data } = await axios.get(
    "https://pokeapi.co/api/v2/pokemon?limit=10&offset=0"
  );

  const pokemonArray = await Promise.all(
    data.results.map(async (pokemon) => {
      const res = await axios.get(pokemon.url);
      return res.data;
    })
  );

  return pokemonArray;
};

export default function Home() {
  const { data } = useQuery("pokemons", fetchPokemons);
  return (
    <>
      <div>
        {data.map((pokemon) => (
          <Pokemon key={pokemon.name} pokemon={pokemon}/>
        ))}
      </div>
    </>
  );
}

export async function getStaticProps() {
  const queryClient = new QueryClient();
  await queryClient.prefetchQuery("pokemons", fetchPokemons);

  return {
    props: {
      dehydratedState: dehydrate(queryClient),
    },
  };
}
于 2021-01-05T03:43:31.567 回答