问题
I have just been schooled on arrow functions, and how they can aid with visibility when you start using sub-functions, here: react native and globally accessible objects
I am not sure if this is different for "if" statements, but I can't get this to work at all. The issue:
myFunction() {
console.log('Welcome Flag: ' + this.props.welcomeFlag);
if (this.props.welcomeFlag == false) {
this.props.dispatch(setWelcomeFlag(true));
showMessage('Welcome back, ' + this.props.userName + '!', { duration: 3000 });
}
}
In this example, the console logs the initial value of welcomeFlag, which is "false". I would then like to, if it is false, display a message to the user and set it to true. Super simple stuff.
It falls over here:
this.props.dispatch(setWelcomeFlag(true));
Because my if statement is not an arrow statement.
Except I can't get the arrow statement to work for if statements. It is working for other kinds of statements but just not for these.
I have tried the answers listed here:
how to use if-else conditon in arrow function in javascript?
But none of these work.
Anyone have any ideas?
回答1:
myFunction()
is a class level function. Binding anything to this
is referring a class itself, therefore you need to bind it to access this
property, otherwise you won't be able to access the class level props.
Although there are many ways to bind this as explained here, but the simplest one would be to use the shorthand arrow syntax as
myFunction = () =>
来源:https://stackoverflow.com/questions/50212127/react-native-arrow-functions-and-if-statements