反应本机箭头功能和if语句 [英] react native arrow functions and if statements

查看:90
本文介绍了反应本机箭头功能和if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚接受过箭头功能的培训,以及当您开始使用子功能时如何使用它们来帮助提高可见性,请参见:

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

我不确定"if"语句是否有所不同,但是我根本无法使用它.问题:

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

在此示例中,控制台记录了welcomeFlag的初始值,即"false".然后,如果它为假,我想向用户显示一条消息并将其设置为true.超级简单的东西.

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.

它落在这里:

this.props.dispatch(setWelcomeFlag(true));

因为我的if语句不是箭头语句.

Because my if statement is not an arrow statement.

除了我无法使arrow语句适用于if语句.它适用于其他类型的语句,但不适用于这些语句.

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:

如何使用if-else条件javascript中的箭头功能?

但是这些都不起作用.

有人有什么主意吗?

推荐答案

myFunction()是类级别的函数.将任何内容绑定到this都是在引用一个类本身,因此您需要将其绑定以访问this属性,否则将无法访问类级别的道具.

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 = () =>

这篇关于反应本机箭头功能和if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆