[英]Imported function is undefined in React
In file1.js:在 file1.js 中:
const doSomething = () => {
console.log('yay');
};
export { doSomething };
//simplified, not using export default due to multiple exports
In file2.jsx:在 file2.jsx 中:
import { doSomething } from './file1.js';
doSomething(); //undefined
Been trying to solve this for a while now.试图解决这个问题已经有一段时间了。 Trying to import this method from one class and add it as an onClick for a component, but it's always undefined.
尝试从一个类导入此方法并将其添加为组件的 onClick,但它始终未定义。 Help would be appreciated
帮助将不胜感激
edit1: fixed import in simplified code edit1:在简化代码中修复导入
You can try this.你可以试试这个。 import file1.js in file2.js like this
像这样在 file2.js 中导入 file1.js
import * as demo from './file1.js';
and call your function like this并像这样调用你的函数
demo.doSomething()
The problem is you are calling the functions which will not return anything.问题是您正在调用不会返回任何内容的函数。
if you do console.log(doSomething())
, you will get logs like this.如果你执行
console.log(doSomething())
,你会得到这样的日志。
yay //you called a functions its executed
undefined // you called a function which will not return anything
first log is from doSomething
file1.js
file.第一个日志来自
doSomething
file1.js
文件。
second log is from file2.jsx
第二个日志来自
file2.jsx
Change Function Expression to Function Declaration.将函数表达式更改为函数声明。 Function Declaration is create's by interpretor before application is started.
函数声明是在应用程序启动之前由解释器创建的。
Function Expression creates a variable that is equal to undefined.函数表达式创建一个等于 undefined 的变量。
file2
execute before file1
, doSomething variable is undefined.file2
在file1
之前执行,则 doSomething 变量未定义。file1
execute before file2
, doSomething variable is link to function.file1
在file2
之前执行,则 doSomething 变量是指向函数的链接。fil1.js文件1.js
export const doSomething = () => {
console.log('yay');
};
file2.js文件2.js
import { doSomething } from './file1.js';
doSomething();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.