Saturday 6 January 2018

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

itemprop="text">

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
}}
>


eventKey="home">

src={Dash}/>




to="/">Dashboard






/>



Sites




eventKey="tours">

to="/tours">



to="/tours">Tours











to="/media">Media






/>




Add new
Site





to="/language">




to="/language">Language






/>



Profile







onClick={this.langEn}>EN
onClick={this.langEs}>ES






);


}
}

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


itemprop="text">
class="normal">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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...