getServerSideProps (Nextjs) 中的无效挂钩调用

IT技术 reactjs next.js
2022-07-08 00:56:19
export const getServerSideProps: GetServerSideProps = async (context) => {
  const { isLoading, error, data } = useQuery('repoData', () =>
    fetch(
      'https://api.github.com/repos/tannerlinsley/react-query'
    ).then((res) => res.json())
  )
  console.log({ data })

  return {
    props: {
      data,
    },
  }

尽管在stackoverflow中有很多与react invalid hook call相关的问题,但仍然没有一个能够解决我的问题。

3个回答

你不能在getServerSideProps. 相反,您可以获取数据并将其useQuery作为初始数据传递给组件中的钩子,如SSR 文档中所述:

export async function getStaticProps() {
  const posts = await getPosts()
  return { props: { posts } }
}

function Posts(props) {
  const { data } = useQuery('posts', getPosts, { initialData: props.posts })

  // ...
}

根据官方文档,这是正确的方法。

const getPosts = () =>
  fetch('https://api.github.com/repos/tannerlinsley/react-query').then((res) =>
    res.json()
  )
export const getServerSideProps: GetServerSideProps = async (context) => {
  const queryCache = new QueryCache()

  await queryCache.prefetchQuery('posts', getPosts)

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

家庭组件

 const { data } = useQuery('posts', getPosts)

getServerSideProps钩子吗?如果是这样,您必须调用它useServerSideProps

(在@Patrick_Roberts 评论后编辑,说它不是钩子而是特殊功能)

然后你不能在其中调用useQuery(任何以它开头的use都被认为是一个钩子)......如果useQuery不是一个钩子,那么你应该重命名它。如果它是无法重命名的外部函数,只需禁用此行的 linter 错误。

https://en.reactjs.org/docs/hooks-rules.html