Invalid Hook call error
When debugging the local component library code, link to the main project reported the following error
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://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.Copy the code
However, after publishing the code to the local repository, install should come down without problem.
Error reason
The React documentation explains why.
In order for the Hook to work properly, the React dependencies in your application code and the React dependencies used inside the React-DOM package must be resolved into the same module.
That is, there are two react instances in your app, and the react instance referenced in the React-DOM is not the same as the react instance directly imported. The react instance referenced by the react-DOM was installed in the local component library. The react-dom instance was installed in the local component library. Not the installed React instance in the main application.
Why is there no problem with NPM install and no problem with NPM link
NPM install merges dependencies in the outermost node_modules. So there is only one dependency. NPM link refers directly to the local directory. Node_modules of the local directory and node_modules of the main project have two references at the same time.
How to solve this problem
To solve this problem, you need to point the component library’s react- DOM dependency to the installed react instance in the main node_modules project. We can do this in two ways.
- Use link to point the component library’s React dependency to the main project’s React dependency
cd [PACKAGE]
npm link [PROJECT]/node_modules/react
Copy the code
- Use alias to specify the React load directory for Nodejs
// /build/wepack.base.config.js alias: { react: path.join(__dirname, ".. /node_modules/react"), }Copy the code
reference
React Github Issue npm-link and Invalid Hook call error