无效的钩子调用错误,但一切似乎都很好

Invalid hook call error, but everything seems to be good

大家好,这是我第一次在这里问问题,但我真的运行对此一无所知...

Uncaught 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

对于 React-native web 上的 React-native 项目 运行,我想 运行 在我的组件中使用 useEffect() 挂钩的初始化函数。为了从我用 yarn link 导入的本地库中获取数据( 该库不使用 react)。

正如你所看到的,我的钩子在一个功能组件中:

import React, { useEffect } from 'react';

import Premium from './Premium';

const Widget = () => {

  useEffect(() => {
    init();
  }, []);

  const init = async () => {
    console.log('working');
  };

  return (
    <Premium />
  );
};

export default Widget;

我还检查了我的 react 和 react-dom 版本,正如上面所说 here 我只有一份 react / react-dom 和 react-native .

可以肯定的是,我已经按照官方文档中的说明用两种不同的方式进行了检查。 (通过 npm ls react-native 也通过 console.log(window.React1 === window.React2);

这是我的 package.json :

  "scripts": {
    "lint": "./node_modules/.bin/eslint .",
    "test": "./node_modules/.bin/jest"
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.10.3"
  },
  "devDependencies": {
    "@babel/core": "7.9.6",
    "@poool/eslint-config": "0.0.1-alpha.3",
    "babel-eslint": "10.1.0",
    "babel-jest": "26.0.1",
    "enzyme": "3.11.0",
    "enzyme-adapter-react-16": "1.15.2",
    "eslint": "6.8.0",
    "eslint-config-standard": "14.1.1",
    "eslint-plugin-babel": "5.3.0",
    "eslint-plugin-import": "2.20.2",
    "eslint-plugin-node": "11.1.0",
    "eslint-plugin-promise": "4.2.1",
    "eslint-plugin-react": "7.20.0",
    "eslint-plugin-standard": "4.0.1",
    "jest": "26.0.1",
    "jest-canvas-mock": "1.1.0",
    "metro-react-native-babel-preset": "0.59.0",
    "react": "16.11.0",
    "react-dom": "16.11.0",
    "react-native": "0.62.2",
    "react-native-web": "0.12.2",
    "react-test-renderer": "16.9.0"
  }
}

谢谢大家!如果我做错了什么,请随时告诉我,这对我来说是第一次:)

我终于自己找到了答案,但我没有提供足够的问题细节。

事实是我有 2 node_modules :

  • 一个用于我的组件(我正在开发一个库)。
  • 其中一个是通过 react-native for web 为 运行 我的组件制作的示例应用程序。

为了解决我的问题,我简单地遵循 https://github.com/facebook/react/issues/13991#issuecomment-435587809(我看到了 10000 次),以便指向同一个 React 副本。而且效果很好!

感谢您的评论!

我注意到当您在浏览器中两次 运行 reactreact-dom 时也会出现此错误。例如,如果它与主应用程序捆绑在一起,但也捆绑在来自 npm 的插件中。

简而言之,运行在浏览器中两次调用 react 代码是行不通的,而且还会导致这个令人困惑的错误。