gpt4 book ai didi

ios - React-native 阻止函数异步执行?

转载 作者:行者123 更新时间:2023-11-28 18:09:09 27 4
gpt4 key购买 nike

在我的 React Native 应用程序中单击一个按钮后,我调用了两个函数:getSolutionListFromDatabase,它设置组件的状态以包含此解决方案列表,然后是 updateDatabaseSolutionList ,它将一个元素添加到此列表并将其推送回 Firebase。但是,尽管应用程序的状态在第一个函数中得到了正确更新,但在第二个函数中,状态被记录为未定义,并且我在第一个函数中的某些语句之前调用了该函数的日志语句。这些函数是否由于某种原因异步运行,这是 React native 的一个特性吗?如果是这样,在设置状态之前如何防止第二个函数执行?谢谢。

onSubmitPressed: function() {
if (this.checkSolution) {
this.getSolutionListFromDatabase();
this.updateDatabaseSolutionList();
Alert.alert(
'Correct!',
"Woohoo!"
);
}
},

getSolutionListFromDatabase: function() {
var thisItemRef = itemsListRef.child(this.state.itemID);
thisItemRef.once('value', (snap) => {
var solutionList = snap.val();
this.setState({
solutionList: solutionList
});
console.log('solution is set as' + this.state.solutionList);
});
},

updateDatabaseSolutionList: function() {
var newSolutionList = [];
console.log('solutionList undefined here' + this.state.solutionList);

if (this.state.solutionList) {
newSolutionList = this.state.solutionList;
newSolutionList.push(this.props.itemID);
}

//then push new list to Firebase
},

最佳答案

逻辑将始终与 answer to your previous question 中的逻辑相同.如果事件之间存在依赖关系,则应将调用移至第一个回调中:

onSubmitPressed: function() {
if (this.checkSolution) {
this.getSolutionListFromDatabase();
}
},

getSolutionListFromDatabase: function() {
var thisItemRef = itemsListRef.child(this.state.itemID);
thisItemRef.once('value', (snap) => {
var solutionList = snap.val();
this.setState({
solutionList: solutionList
});
console.log('solution is set as' + this.state.solutionList);
this.updateDatabaseSolutionList();
});
},

updateDatabaseSolutionList: function() {
var newSolutionList = [];
console.log('solutionList undefined here' + this.state.solutionList);

if (this.state.solutionList) {
newSolutionList = this.state.solutionList;
newSolutionList.push(this.props.itemID);
}

Alert.alert(
'Correct!',
"Woohoo!"
);
//then push new list to Firebase
},

如果您将先决条件(即 solutionList)传递给需要它的函数,而不是使用字段/属性,这种类型的流程将变得更容易自己遵循:

onSubmitPressed: function() {
if (this.checkSolution) {
this.getSolutionListFromDatabase();
}
},

getSolutionListFromDatabase: function() {
var thisItemRef = itemsListRef.child(this.state.itemID);
thisItemRef.once('value', (snap) => {
var solutionList = snap.val();
this.updateDatabaseSolutionList(solutionList);
});
},

updateDatabaseSolutionList: function(solutionList) {
solutionList.push(this.props.itemID);

Alert.alert(
'Correct!',
"Woohoo!"
);
//then push new list to Firebase
},

但更好的方法是直接将新值 push() 直接发送到 Firebase,而不是先下载整个数组,然后将其发送回去并添加一个新项目:

onSubmitPressed: function() {
if (this.checkSolution) {
itemsListRef.child(this.state.itemID).push(...);
}
},

关于ios - React-native 阻止函数异步执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37232641/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com