Next.js 使用 Typescript:挂钩调用无效。钩子只能在函数组件的内部调用

Next.js with Typescript: Invalid hook call. Hooks can only be called inside of the body of a function component

在使用 next.jstypescript 的全新项目中,我在功能性反应组件中收到以下错误。

Invalid hook call. Hooks can only be called inside of the body of a function component

在错误的引用中,它实际上显示了正在使用状态的功能组件:

我已查看 https://reactjs.org/warnings/invalid-hook-call-warning.html

中的建议
  1. 我不认为我违反了钩子的规则:

    Call[ing] them at the top level in the body of a function component.

  2. 我不认为我有两个版本的 React,我正在使用 yarn 并且我添加了解决方案以仅使用一个版本的 Reacthttps://yarnpkg.com/lang/en/docs/selective-version-resolutions/)

我真的不知道我还能做些什么来解决这个问题,所以我发布了最小的 repo 来重现这个问题:https://github.com/coler-j/shopify_playground

组件:

import React, { useState, useCallback } from 'react'
import {
  Layout,
  Page,
  Card,
  Button,
  FormLayout,
  TextField
} from '@shopify/polaris'

export default function App() {
  const [first, setFirst] = useState('')
  const handleFirstChange = useCallback(value => setFirst(value), [])

  return (
    <Page title="Polaris">
      <Layout>
        <Layout.AnnotatedSection title="Form" description="A sample form using Polaris components.">
          <Card sectioned>
            <FormLayout>
              <FormLayout.Group>
                <TextField value={first} label="First name" placeholder="Tom" onChange={handleFirstChange} />
              </FormLayout.Group>
              <Button primary>Submit</Button>
            </FormLayout>
          </Card>
        </Layout.AnnotatedSection>
      </Layout>
    </Page>
  )
}

推送我的 Next.js 项目 之后,我 运行 遇到了类似的问题(这是 100 %工作)到Github然后 - 几乎立即 - 克隆回同一台计算机(运行 Windows10).

虽然错误对话框抱怨“无效挂钩调用”,但我终端中的错误 watefar 实际上抱怨 invalid directory casing。我尝试切换到一些基于 UNIX 的终端,但无济于事。

我删除了 node_modules.next 目录并尝试从 PowerShell 进行全新安装。问题消失了……

我认为最初导致该问题的原因是我在第一个 yarn install 中使用了默认的 Windows 命令行(它比 Windows 终端启动快一点,我不耐烦),不知何故弄乱了外壳。但我不确定。

使用 Docker 容器绝对是更稳健和面向未来的解决方案……