简体   繁体   English

如何避免在使用 es6 的反应中使用绑定?

[英]How to avoid using binding in react using es6?

i am using window.onerror to log javascript errors to a file like in code below,我正在使用 window.onerror 将 javascript 错误记录到文件中,如下面的代码所示,

class ErrorComponent extends react.purecomponent {
    constructor(props) {
        super(props);
        this.handle_error = this.handle_error.bind(this);
    }

    componentDidMount = () => {
        window.onerror = this.handle_error;
    }

    handle_error = (message, source, lineno, colno, error) => {
        const payload = {
            'message': message,
            'source': source,
        };
        return false;
    }

    render = () => {
        return null;
    }
}

So from above code it is seen i have used bind.所以从上面的代码可以看出我使用了绑定。 if i dont bind handle_error and call like below in componentdidmount如果我不绑定 handle_error 并在 componentdidmount 中调用如下所示

componentDidMount () {
    window.onerror = this.handle_error();
}

And when i log the the message and source values in handle_error i get them as undefined.当我在 handle_error 中记录消息和源值时,我将它们设为未定义。

How can i solve it...I dont want to use bind and how can i fix this without binding handle_error method.我该如何解决它...我不想使用绑定以及如何在不绑定 handle_error 方法的情况下解决此问题。 could someone help me with this.有人可以帮我解决这个问题吗? thanks.谢谢。

Use a fat arrow function使用粗箭头函数

The fat arrow function should also pass the this context to the handle_error function.胖箭头函数还应该将this上下文传递给handle_error函数。

class ErrorComponent extends react.purecomponent {
    componentDidMount = () => {
        window.onerror = (message, source, lineno, colno, error) => this.handle_error(message, source, lineno, colno, error);
    }

    handle_error = (message, source, lineno, colno, error) => {
        const payload = {
            'message': message,
            'source': source,
        };
        return false;
    }

    render = () => {
        return null;
    }
}

The 'problem' or inconvenience you are facing is one of the very reasons arrow function expression (aka 'fat arrow function') was implemented.您面临的“问题”或不便正是实现箭头函数表达式(又名“胖箭头函数”)的原因之一。

You can read more about them here . 您可以在此处阅读有关它们的更多信息

Your example code using arrow function expression is below.您使用箭头函数表达式的示例代码如下。 Please note passing arguments onerror .请注意传递参数onerror

 class ErrorComponent extends react.purecomponent { componentDidMount = () => { window.onerror = (message, source, lineno, colno, error) => this.handle_error(message, source, lineno, colno, error); } handle_error = (message, source, lineno, colno, error) => { const payload = { 'message': message, 'source': source, }; return false; } render = () => { return null; } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM