首页 > 解决方案 > 使用 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未定义。

标签: javascript

解决方案


在构造函数中绑定导入的函数:

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);
}

推荐阅读