Hooks error: Invalid Hook Call using NextJS or ReactJS on Windows
Hooks error: Invalid Hook Call using NextJS or ReactJS on Windows
尝试在 NextJS 中使用 React Hooks 时,我继续收到以下错误:
Hooks can only be called inside the body of a function component.
此问题只发生在 Windows 上,使用 Mac 时工作正常。
这是一个有据可查的问题,我已经解决了许多建议的解决方案,包括:
- 多个版本的 React 或 React DOM
- 修改
next.config.js
中的 webpack 设置
- 链接到特定节点模块包
这是一个使用示例:
import React, { useState, useEffect } from 'react'
const Index = () => {
const [ test, setTest ] = useState('Test')
useEffect(() => (
console.log(`Page loaded, variable value: ${test}`)
), [])
return <div>Hello</div>
}
我正在使用以下版本:
"next": "^9.1.1",
"react": "^16.10.2",
"react-dom": "^16.10.2"
如果您仅在 Windows 遇到此问题,这可能与您导航到项目文件夹的方式有关。确保您在所有文件夹中使用正确的字符大小写!在我的场景中,我使用 Powershell 导航到我的项目和 运行 开发服务器。
例如下面会导致Hook错误:
cd desktop/project_folder
npm run dev
问题是“桌面”是大写的目录名称。因此,运行通过以下步骤连接服务器非常有效:
cd Desktop/project_folder
npm run dev
如果您使用不正确的大小写打开 project_folder,然后使用交互式 shell 到 运行 开发服务器,也会发生此问题,例如:
cd desktop/project_folder
## Open project_folder in VS Code
code .
## Start development server from VS Code's interactive shell
npm run dev
问题的根源在于,我认为由于预期路径名称的变化导致模块路径被错误导入。如果您看到来自您的开发服务器的以下警告,请确保首先解决它:
There are multiple modules that exist that only differ in casing
尝试在 NextJS 中使用 React Hooks 时,我继续收到以下错误:
Hooks can only be called inside the body of a function component.
此问题只发生在 Windows 上,使用 Mac 时工作正常。
这是一个有据可查的问题,我已经解决了许多建议的解决方案,包括:
- 多个版本的 React 或 React DOM
- 修改
next.config.js
中的 webpack 设置
- 链接到特定节点模块包
这是一个使用示例:
import React, { useState, useEffect } from 'react'
const Index = () => {
const [ test, setTest ] = useState('Test')
useEffect(() => (
console.log(`Page loaded, variable value: ${test}`)
), [])
return <div>Hello</div>
}
我正在使用以下版本:
"next": "^9.1.1",
"react": "^16.10.2",
"react-dom": "^16.10.2"
如果您仅在 Windows 遇到此问题,这可能与您导航到项目文件夹的方式有关。确保您在所有文件夹中使用正确的字符大小写!在我的场景中,我使用 Powershell 导航到我的项目和 运行 开发服务器。
例如下面会导致Hook错误:
cd desktop/project_folder
npm run dev
问题是“桌面”是大写的目录名称。因此,运行通过以下步骤连接服务器非常有效:
cd Desktop/project_folder
npm run dev
如果您使用不正确的大小写打开 project_folder,然后使用交互式 shell 到 运行 开发服务器,也会发生此问题,例如:
cd desktop/project_folder
## Open project_folder in VS Code
code .
## Start development server from VS Code's interactive shell
npm run dev
问题的根源在于,我认为由于预期路径名称的变化导致模块路径被错误导入。如果您看到来自您的开发服务器的以下警告,请确保首先解决它:
There are multiple modules that exist that only differ in casing