Reputation: 1112
I have a problem with the arrow function in my React project.
The class looks like this:
f1() {
// sth...
}
f2 = (a) => () => { /* sth */ }
f3 = (b) => () => {
this.f1();
this.f2();
}
Why the function f2 is not being called? F1 is ok but f2 seems to have a problem with context? How to solve it? I need to call the same function(f2) in another place where it works (onClick event). I guess there is a problem with 'this' that is auto binded but I don't know how to solve it. Please help.
Upvotes: 1
Views: 679
Reputation: 674
Try it like this.
componentWillMount() {
this.f3(1);
}
f1() {
console.log('calling f1');
}
f2 = (a) => {
console.log('calling f2 ' + a);
}
f3 = (b) => {
this.f1();
this.f2('text');
}
Upvotes: 1
Reputation: 7136
Your function f2
is indeed beeing called, but returns another function.
f2 = (a) => () => { /* sth */ }
this is equivalent to :
f2 = (a) => {
return () => { /* sth */ }
}
So to call /* sth */
, you have to use this :
f2()()
Because f2()
returns your second function (the inner one).
Upvotes: 7
Reputation: 880
As suggested by @Jonas W. and @Seblor, you're creating functions returning functions. Instead use the syntax below:
f1() {
// sth...
}
f2 = (a) => { /* sth */ }
f3 = (b) => {
this.f1();
this.f2();
}
Upvotes: 0
Reputation: 281656
Function f3 is a function that returns another function and in order to invoke it, you need to write it like
f3 = (b) => () => {
this.f1();
this.f2();
}
this.f3()()
Upvotes: 2