代码在componentDidMount中执行,但在其他函数中不执行

时间:2017-10-21 05:21:44

标签: react-native google-cloud-firestore react-native-firebase

所以我遇到了一个奇怪的问题,也许我在这里做错了但我之前没有遇到过这个问题而且我的应用程序充满了类似的代码。

基本上我正在尝试在附加到onPress按钮的函数中做一个简单的Firestore get()。由于某种原因,代码没有运行,或者如果是,我没有得到任何反馈。如果我在componentDidMount中放入相同的代码,它会运行并为我提供数据库快照。

以下是有问题的两位代码。

针对我正在使用的当前绑定进行了更新

    this.usersRef = firebase.firestore().collection('users');

componentDidMount() {
    this.usersRef
        .get()
        .then((snapshot) => {
            console.log('TEST didMount snapshot', snapshot);
        }).catch((error) => {
            console.log(error)
        });
}


    submitSearch() {
        console.log('submitSearch')
        this.usersRef
            .get()
            .then((snapshot) => {
                console.log('TEST submitSearch snapshot', snapshot);
            }).catch((error) => {
                console.log(error)
            });
}

从这里调用submitSearch

            <Button style={{marginTop: 3, marginBottom: 8}} primary onPress={() => this.submitSearch()}>
                {strings.search}
            </Button>

所以我在这里尝试了很多东西,我似乎无法弄清楚为什么代码在submitSearch函数中不起作用。我从该函数中看到的唯一一件事就是控制台日志说提交搜索。

任何想法将不胜感激!感谢。

1 个答案:

答案 0 :(得分:0)

问题在于函数的绑定方式。

我最初在构造函数中有以下内容: this.submitSearch = this.submitSearch.bind(this)

并使用

在按钮组件中调用它

onPress={this.submitSearch}

我删除了构造函数绑定,并在按钮组件中仅使用了以下内容:

onPress={() => this.submitSearch()}

我以为我已经做到了!但我可以确认这解决了这个问题。奇怪的是,没有任何警告或错误,看起来像是一个有用的场景,而不仅仅是没有运行代码。

相关问题