首页 > 解决方案 > NextJS - 无效的挂钩调用。Hooks 只能在函数组件的主体内部调用

问题描述

尝试使用 NextJS 构建时出现此错误。我不使用样式组件。我尝试删除 node_modules 等,但没有运气。react我尝试在我的 next.config.js 文件和 package.json 中添加别名并解析,但没有成功。我正在使用 react 16.8.6、react-dom 16.8.6 和下一个 9.0.4。npm ls说每个只有一个。该应用程序使用material-ui。我没有使用任何 npm 链接。我在一个没有任何钩子的版本和一个只有功能组件和钩子的版本中得到了错误。

回购在这里:https ://github.com/dancancro/questions/tree/convert-to-function-component

Codesandbox 在这里:https ://codesandbox.io/s/stop-indoctrination-5xfpi

错误在这里:https : //gist.github.com/dancancro/2dfafb053aaaedfade406fd4f67eb68a render -> renderToString -> ReactDOMServerRenderer.read -> ReactDOMServerRenderer.render -> Object.WithStyles [as render] ...

有问题的钩子是useStyles()在函数中调用此文件的第 17428 行withStyles。搜索“var classes = useStyles(props)”。问题在于 nextjs 生成的代码。我写的代码没有使用withStyles或任何以“use*”开头的钩子或任何函数

https://raw.githubusercontent.com/dancancro/questions/invalid-hook-call/.next/static/development/pages/index.js

标签: reactjsmaterial-uinext.js

解决方案


从 next.config.js 中删除它解决了这个问题。

    webpack: config => {
        config.externals = [
            '/'
        ]
        return config
    },

推荐阅读