问题
While attempting to use React Hooks in NextJS I continue to receive the following error:
Hooks can only be called inside the body of a function component.
This issue only occurs on Windows and works fine using Mac.
This is a well documented issue and I have troubleshot many of the proposed solutions, including:
- Multiple versions of React or React DOM
- Modifying webpack settings in
next.config.js
- Linking to specific node module pacakges
Here is an example of use:
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>
}
I am using the following versions:
"next": "^9.1.1",
"react": "^16.10.2",
"react-dom": "^16.10.2"
回答1:
If you are experiencing this issue ONLY on PC, it may have to do with how you navigate to your project folder. Make sure you are using the correct character case on all of your folders! In my scenario, I used Powershell to navigate to my project and run the development server.
For example, the following will result in a Hook error:
cd desktop/project_folder
npm run dev
The issue is that "desktop" is a capitalized directory name. Therefore, running the server with the following steps works perfectly:
cd Desktop/project_folder
npm run dev
This issue also occurs if you opened your project_folder using incorrect casing and then use an interactive shell to run the development server, for example:
cd desktop/project_folder
## Open project_folder in VS Code
code .
## Start development server from VS Code's interactive shell
npm run dev
At the root of the issue, I believe module paths are incorrectly being imported due to a variation of expected path names. If you see the following warning coming from your development server, make sure to address it first:
There are multiple modules that exist that only differ in casing
来源:https://stackoverflow.com/questions/58365151/hooks-error-invalid-hook-call-using-nextjs-or-reactjs-on-windows