React 中 ‘X’ is not defined react/jsx-no-undef 错误
React.js 错误“X is not defined react/jsx-no-undef”发生在我们忘记在代码中导入函数、类或变量之前使用它。 要解决该错误,请确保在我们的代码中使用之前导入该值,例如 import {myFunc} from ‘my-package’。
// 👉️ forgot to import useState
const App = () => {
// ⛔️ 'useState' is not defined no-undef
// Uncaught ReferenceError: useState is not defined
const [count, setCount] = useState(0);
const handleClick = event => {
setCount(current => current + 1);
};
return (
<div>
<h2>Count: {count}</h2>
<button onClick={handleClick}>Increment</button>
</div>
);
};
export default App;
上面示例中的问题是我们忘记在使用前导入 useState 钩子。
为了解决错误,我们必须导入函数。
import {useState} from 'react';
我们的错误消息应包含我们必须导入的函数的名称。
ES6 中有两种类型的导入——命名导入和默认导入。
// 👇️ named import
import {myFunc1} from 'my-package';
// 👇️ default import
import myFunc2 from 'my-package';
我们必须使用哪种类型的导入来导入函数取决于它是如何导出的。
如果我们在使用本地成员(不是来自第三方包)时遇到错误,请确保在导入语句中指定相对路径。
// 👇️ named import
import {myFunc1} from './another-file';
// 👇️ default import
import myFunc2 from './another-file';
上面的示例假设我们有一个名为 another-file.js 的文件,它位于与 App.js 相同的目录中。
确保从 another-file.js 导出我们尝试使用的函数。
// 👇️ named export
export const myFunc1 = () => {
console.log('hello world');
}
// 👇️ default export
export default function myFunc2() {
console.log('hello world');
}
例如,如果我们需要从一个目录向上导入,我们将导入为 import {myFunc1} from ‘../another-file’。
导入所有正在使用的函数后,错误将得到解决。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。