How can I bind this to the React component when dealing with a nested function?
Here is a skeleton example. The reason that function2 is nested is so that you can get access to the variables defined in function1
class View extends Component{
constructor(props){
this.function1 = this.function1.bind(this);
this.state = {
a = null;
}
}
componentDidMount(){
function1();
}
function1(){
console.log(this); //will show the component correctly
var param1 = 10;
//call a second function that's defined inside the first function
function2();
function function2(){
console.log(this); //undefined
var a = param1*2;
this.setState({ a : a}); //won't work because this is undefined
}
}
render(){
return(
<div>
<p> Hello </p>
</div>
)
}
}
function2? It's only accessible withinfunction1and you're not calling it.const function2 = () => {...}- though, you never use function2, so there's no issue