javascript - 使用 bind() call() 或 apply() 时,`this` 没有被传递给函数
问题描述
我正在使用 React,在我的内部我componentDidMount() {}
正在调用一个导入的函数并希望在this.setState
其中访问。
在 内componentDidMount
,当 I 时console.log(this)
,我得到了预期的组件。
但如果我运行myFunction.call(this)
,console.log(this)
内部 myFunction 会返回undefined
。
任何想法为什么this
没有被正确传递?
编辑1:添加代码。
零件:
class Navbar extends React.Component {
componentDidMount() {
myFunction.call();
}
}
myFunction.js:
export const myFunction = () => {
console.log('this:', this);
}
控制台输出:
this: undefined
edit2:有些人将此标记为“我可以绑定箭头函数”的副本,但 myFunction 是一个箭头函数,即使我直接调用它而不是使用 .call() 它也会产生相同的结果:this
未定义。
解决方案
在构造函数中绑定导入的函数:
import { myFunction } from './path/to/myFunction';
class Navbar extends React.Component {
constructor() {
/* other constrcutor code */
myFunction = myFunction.bind(this);
}
componentDidMount() {
myFunction();
}
}
在您的myFunction.js
中,将 ES6 箭头函数转换为常规 ES5 函数(请参阅Can you bind arrow functions?):
export const myFunction = function() {
console.log('this:', this);
}
推荐阅读
- flutter - 使用 Flutter Form 进行异步验证
- c# - 如何使用参数从另一个任务创建自定义用户控件
- typescript - 我正在尝试让我的 js 库支持 ts
- jquery - 抓取 iframe 的内容并将其放在 div 类中
- python - 为什么我的 Python 脚本不与 PHP(shell_exec) 通信?
- javascript - 如何在反应三个js中过滤点击?
- flutter - Flutter 总是重启而不是热重载
- flutter-web - 将移动应用程序转换为 Web 应用程序时出错
- groovy - 如何在 Groovy 中附加列表列表
- sql - 在数组中编写 PLSQL 选择