javascript - 为什么调用 .bind(this) 时函数中 this 未定义?

标签 javascript reactjs

在我的组件中,我正在调用另一个文件中定义的函数,如下所示:

import React from 'react';
import { widgetComponentDidMount } from "../../SharedData/widget";

export default class Component extends React.Component {

    constructor(props) {
        super(props);
    };

    componentDidMount(){
        widgetComponentDidMount(this).bind(this);
    }

    //render, etc

};

但是当我将调试器放入函数的定义中时,“this”未定义:

export function widgetComponentDidMount() {
    var _this = this;
    debugger
    //_this is undefined
}

我知道我可以将其作为参数传递并以这种方式引用它,但我宁愿避免每次都传递它。这不就是bind的目的吗?我只能在同一个文件中使用它。知道为什么它未定义以及如何访问“this”而不将其作为参数传递吗?

最佳答案

您在调用bind之前执行该函数。您必须在执行之前绑定(bind):

widgetComponentDidMount.bind(this)();

如果是我,我实际上会在构造函数方法中执行 bind 并存储结果,这样您就不需要为每次调用创建一个新函数:

export default class Component extends React.Component {

  constructor(props) {
    super(props);
    this.widgetComponentDidMount = widgetComponentDidMount.bind(this);
  }

  componentDidMount() {
    this.widgetComponentDidMount();
  }
}

关于javascript - 为什么调用 .bind(this) 时函数中 this 未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40030924/

相关文章:

javascript - 在 AngularJS 中第一次使用服务 promise 的旧响应的 Controller 方法

javascript - 使用 reduce、map 和 spread 的笛卡尔积对需要展平的结果进行分组

Javascript - 从列表返回值

javascript - React useEffect 如何监视和更新状态?

Javascript:我在哪里放置带有标准数据的数组?

javascript - 更改移动浏览器的点击事件

javascript - JSX 如何从循环中获取计数器并显示状态

javascript - 何时将更新推送到 REST 后端

javascript - 在 React.JS 中将 props 的值从函数传递给 render()

javascript - 从 React router 3 更新到 4.1.1,我如何将我的路由与 app.jsx 分开?