i am using window.onerror to log javascript errors to a file like in code below,
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
componentDidMount () {
window.onerror = this.handle_error();
}
And when i log the the message and source values in handle_error i get them as undefined.
How can i solve it...I dont want to use bind and how can i fix this without binding handle_error method. could someone help me with this. thanks.
The fat arrow function should also pass the this
context to the handle_error
function.
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
.
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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.