I'm trying to unearth the cause of some strange behavior in the binding of this
in a React component.
I'm used to developing components and placing their methods in the class body and binding them to the component's this
within the constructor
. However, I recently decided I wanted to clean things up and separate concerns by extracting some of these large methods to separate files, and then importing them into the component.
To my dismay, binding this
does not work as easy in this case. Even stranger, while the use of an ES6 arrow function seems to not bind properly, the use of a basic ES5 function is working fine. I'm trying to figure out the cause of this behavior:
Example 1 [WORKS AS EXPECTED]
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.changeName = this.changeName.bind(this);
this.state = {
name: 'John'
};
}
changeName() {
this.setState({
...this.state,
name: 'Jane'
});
}
...
Example 2 [NOT WORKING -- TypeError: Cannot read property 'setState' of undefined]
App.js
import React, { Component } from 'react';
import changeName from './change-name';
class App extends Component {
constructor(props) {
super(props);
this.changeName = changeName.bind(this);
this.state = {
name: 'John'
};
}
...
change-name.js
const changeName = () => {
this.setState({
...this.state,
name: 'Jane'
});
};
export default changeName;
Example 3 [WORKS AS EXPECTED -- Same App.js
as Example 2]
change-name.js
function changeName() {
this.setState({
...this.state,
name: 'Jane'
});
};
module.exports = changeName;