代码在 componentDidMount 中执行,但不在其他函数中执行
Code executes in componentDidMount but not in Other functions
所以我 运行 遇到了一个奇怪的问题,也许我在这里做错了什么,但我以前没有遇到过这个问题,而且我的应用程序充满了类似的代码。
基本上,我正在尝试在附加到 onPress 按钮的函数中执行一个简单的 Firestore get()。由于某种原因,代码不是 运行,或者如果是,我没有收到任何反馈。如果我将相同的代码放在 componentDidMount 中 运行s 并给我数据库快照。
这是有问题的两位代码。
更新了我正在使用的当前绑定
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 函数中不起作用。我从该功能中唯一看到的是控制台日志,上面写着提交搜索。
如有任何想法,我们将不胜感激!谢谢
问题在于函数的绑定方式。
我最初在构造函数中有以下内容:
this.submitSearch = this.submitSearch.bind(this)
并在按钮组件中使用
调用它
onPress={this.submitSearch}
我删除了构造函数绑定并在按钮组件中仅使用了以下内容:
onPress={() => this.submitSearch()}
我以为我已经做到了!但我可以确认这解决了问题。奇怪的是,虽然没有警告或错误,但似乎是一种有用的场景,而不是 运行 代码。
所以我 运行 遇到了一个奇怪的问题,也许我在这里做错了什么,但我以前没有遇到过这个问题,而且我的应用程序充满了类似的代码。
基本上,我正在尝试在附加到 onPress 按钮的函数中执行一个简单的 Firestore get()。由于某种原因,代码不是 运行,或者如果是,我没有收到任何反馈。如果我将相同的代码放在 componentDidMount 中 运行s 并给我数据库快照。
这是有问题的两位代码。
更新了我正在使用的当前绑定
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 函数中不起作用。我从该功能中唯一看到的是控制台日志,上面写着提交搜索。
如有任何想法,我们将不胜感激!谢谢
问题在于函数的绑定方式。
我最初在构造函数中有以下内容:
this.submitSearch = this.submitSearch.bind(this)
并在按钮组件中使用
调用它onPress={this.submitSearch}
我删除了构造函数绑定并在按钮组件中仅使用了以下内容:
onPress={() => this.submitSearch()}
我以为我已经做到了!但我可以确认这解决了问题。奇怪的是,虽然没有警告或错误,但似乎是一种有用的场景,而不是 运行 代码。