【问题标题】:Next.js - Can we call custom hooks in GetStaticProps()Next.js - 我们可以在 GetStaticProps() 中调用自定义钩子吗
【发布时间】:2022-02-09 21:57:08
【问题描述】:

我们有什么方法可以使用 getStaticProps() 中的自定义挂钩。这样做的原因是,我们使用 Contentful CMS 从 Delivery API 获取数据,而且我们更容易使用自定义挂钩来获取某些数据。

现在,当我们在 getStaticProps() 函数中调用例如 useHomePageData 时,我们会在尝试使用简单的对象破坏来获取数据时遇到错误。

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 
1. You might have mismatching versions of React and the renderer (such as React DOM) 
2. You might be breaking the Rules of Hooks 
3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

这是我们在 getStaticProps()

中的代码
export function getStaticProps() {
const { data, isPending, error } = useFetchPagesProps('phasePage');
const { name, title, slug, sections } = data;

return {
 props: {
     name,
     title,
     slug,
     sections
  }
 }
}

我知道这个错误意味着什么,但仍然有人知道任何 npm 库 或类似的东西,以便我们可以使用这个 custom-hook

P.S:我们也在自定义钩子中使用 useEffect() ,这样可能会导致我认为的问题

【问题讨论】:

标签: reactjs next.js


【解决方案1】:

getStaticProps 在技术上与 React 无关。本质上,这只是一个对 Next.js 框架本身具有特殊意义和功能的函数。所以不,你不能在那里使用钩子(至少不能在其中使用 setState useEffect 等。

【讨论】:

    【解决方案2】:

    这违反了React Hooks 规则及其最佳实践,您必须不惜一切代价避免这种心态,但有时您只是想做错事;)。在这种情况下,您可以创建一个有点像全局变量并欺骗React 认为您正在遵守规则,但显然您没有:)。

    代码是这样的:

    //use the hook in one the parents component which you know that would be initialized earlier
    //for example maybe _app.js file
    
    let hackTheHooksRules;
    function MyApp({ Component, pageProps }) {
      hackTheHooksRules = useFetchPagesProps("phasePage");
      return <Component {...pageProps} />
    }
    export default MyApp;
    export hackTheHooksRules;
    

    在你想使用它的目的地,你应该这样做:

    import {hackTheHooksRules} from 'path-to-that-file'
    export function getStaticProps() {
      const { data, isPending, error } = hackTheHooksRules || {};
      const { name, title, slug, sections } = data;
    
      return {
        props: {
          name,
          title,
          slug,
          sections
        }
      };
    }
    

    注意:同样不建议这样做,但有时The heart wants what it wants 你该怪谁?

    这里是你应该尝试遵守的钩子规则:reactjs.org/docs/hooks-rules.html

    【讨论】:

      猜你喜欢
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      相关资源
      最近更新 更多