【发布时间】:2021-06-30 22:53:13
【问题描述】:
我正在使用 typescript 将源 tsx 文件编译为 js。
tsx 文件中的源代码正确使用了 react 钩子,编译后的版本似乎也正确使用了它们。
源代码(tsx)
import React, { useEffect } from "react";
export function Checkbox() : JSX.Element {
useEffect(function() {
console.log("Component mounted!");
});
return (
<div>...</div>
);
}
编译成 (js)
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Checkbox = void 0;
var jsx_runtime_1 = require("react/jsx-runtime");
var react_1 = require("react");
function Checkbox() {
react_1.useEffect(function () {
console.log("Component mounted!");
});
return (jsx_runtime_1.jsx("div", { children: "..." }, void 0));
}
exports.Checkbox = Checkbox;
//# sourceMappingURL=Checkbox.js.map
tsconfig.json
{
"$schema": "http://json.schemastore.org/tsconfig",
"compilerOptions": {
"lib": ["es2020", "dom"],
"module": "commonjs",
"target": "es5",
"baseUrl": "src/ts",
"types": ["node", "react"],
"jsx": "react-jsx",
"outDir": "src/js",
"sourceMap": true,
"strict": true,
"allowJs": true,
"esModuleInterop": true,
"skipLibCheck": true,
"noUnusedParameters": true,
"allowUnreachableCode": false,
"preserveConstEnums": false,
"resolveJsonModule": true
},
"include": ["src/ts/**/*"]
}
我在 chrome 控制台中收到以下错误,说我违反了钩子规则。
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
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
at resolveDispatcher (react.development.js?52c0:1476)
at Object.useEffect (react.development.js?52c0:1519)
at Checkbox (Checkbox.tsx?7b6e:4)
at renderWithHooks (react-dom.development.js?61bb:14985)
at mountIndeterminateComponent (react-dom.development.js?61bb:17811)
at beginWork (react-dom.development.js?61bb:19049)
at HTMLUnknownElement.callCallback (react-dom.development.js?61bb:3945)
at Object.invokeGuardedCallbackDev (react-dom.development.js?61bb:3994)
at invokeGuardedCallback (react-dom.development.js?61bb:4056)
at beginWork$1 (react-dom.development.js?61bb:23964)
我已经在谷歌上搜索了几天,但仍然不知道为什么会发生这种情况......
【问题讨论】:
标签: reactjs typescript react-hooks react-tsx