Sunday 26 February 2017

reactjs - Cannot read property 'setState' of undefined, when running a function



class App extends Component {
constructor(){
super();
this.state = {
sideNav: '',
language: 'en'

}
}

langEn() {
this.setState({language: 'en'}).bind(this);
console.log("Language changed to en");
}

langEs() {
this.setState({language: 'es'}).bind(this);

console.log("Language changed to es");
}

render() {

const mouseEnter = e => {
this.setState({sideNav: "sideNav sidenav---sidenav---_2tBP sidenav---expanded---1KdUL"});
}

const mouseLeave = e => {

this.setState({sideNav: "sidenav---sidenav---_2tBP sidenav---collapsed---LQDEv"});
}


return (


onMouseEnter={mouseEnter}
onMouseLeave={mouseLeave}

className={this.state.sideNav}
onSelect={(selected) => {
// Add your code here
}}
>







Dashboard







Sites








Tours








Media








Add new Site








Language







Profile












);
}
}

export default App;


The error happens when I press one of the two buttons to run the lanEn or lanEs functions. I have tried alternating where they are, placing them in or out of the render() method, removing this using bind. The end goal is change the language state using these buttons and transfer it to different pages using props


Answer



You just need to add this piece of code in the constructor:




this.langEn = this.langEn.bind(this);


What the above code does is, it replaces the existing langEn function with a new function with the this context changed to class App.



If you don't want to manually bind it in the constructor, you can go with arrow functions, which has lexical binding.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...