React Hooks Error: Hooks can only be called inside the body of a function component

后端 未结 17 2111
旧巷少年郎
旧巷少年郎 2020-12-05 04:07

I am getting this error when using the useState hook. I have this in it\'s basic form, looking at the react docs for a reference, but am still getting this erro

17条回答
  •  一整个雨季
    2020-12-05 04:21

    Just to elaborate on @rista404's answer, including duplicate versions of react (and perhaps react-dom) will yield the same error depending on where you are using your hooks. Here are two examples...

    1. An external dependency includes another version of react in its dependencies, likely by mistake as react should usually be a peer dependency. If npm doesn't automatically dedupe this version with your local version, you may see this error. This is what @rista404 was referring to.
    2. You npm link a package that includes react in its devDependencies or dependencies. Now, for modules in this package, you may see errors if they pull a different version of react from the their local node_modules directory rather than the parent project's.

    The latter can be fixed when bundling with webpack by using resolve.alias like so...

        resolve: {
            alias: {
                'react': path.resolve(__dirname, 'node_modules/react'),
                'react-dom': path.resolve(__dirname, 'node_modules/react-dom')
            }
        }
    

    This will ensure react is always pulled from the parent project's node_modules directory.

提交回复
热议问题