React 修复 ‘X’ is not defined react/jsx-no-undef 错误
React.js 错误 “X is not defined react/jsx-no-undef” 发生在我们忘记在使用之前在代码中导入函数、类或变量时。 要解决该错误,需要确保在代码中使用之前导入该值,例如 从 import {myFunc} from 'my-package'
。
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 中有两种类型的导入——命名导入和默认导入。
// ?️ 命名导入
import {myFunc1} from 'my-package';
// ?️ 默认导入
import myFunc2 from 'my-package';
我们必须使用哪种类型的导入来导入函数取决于它是如何导出的。
当我们尝试将本地文件导入为 import ‘./myFile’ 而不是 import myFunction from ‘myFile’ 时,经常会出现“X is not defined error” 的错误。
如果我们在使用本地成员(不是来自第三方包)时遇到错误,请确保在导入语句中指定相对路径。
// ?️ 命名导入
import {myFunc1} from './another-file';
// ?️ 默认导入
import myFunc2 from './another-file';
上面的示例假设我们有一个名为 another-file.js 的文件,该文件与 App.js 位于同一目录中。
确保从 another-file.js 导出我们尝试使用的函数。
// ?️ 命名导出
export const myFunc1 = () => {
console.log('hello world');
}
// ?️ 默认导出
export default function myFunc2() {
console.log('hello world');
}
例如,如果我们需要从一个目录向上导入,则可以导入为 import {myFunc1} from '../another-file'
。
导入所有正在使用的函数后,错误将得到解决。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。