在 componentDidMount 内的一长串 promise 中,我最终设置了一个在构造函数中创建的数组(称为 this.recentCards)来保存从 Firebase 查询检索到的一些数据。之后,我将“正在加载”状态设置为 false,以便我的渲染函数可以在正确加载数据后正确渲染数据。
但是,没有渲染任何数据,我可以看到在渲染函数期间,在“this.state.loading”为 false 的分支中,this.recentCards 为空。这是没有意义的,因为在加载状态设置为 false 之前 this.recentCards 不为空。有谁知道这种相互作用是如何发生的?我找不到任何线索。
这里有一些代码供引用:注意:使用 that.setState 中的“that”是因为我在访问函数 this.setState 时遇到问题,并使用“that”作为保存“this”的变量
Promise.all(promises).then(function(results){
for(var i = 0; i < tagInfo.length; i++){
tempArray.push(
<FeedCard key = {(i + 1) * -1}
handleToUpdate = {this.addView}
mutual = {false}
time = {tagInfo[i]["Time"]}
restaurantid = {tagInfo[i]["Restaurant"]}
isRestaurant = {tagInfo[i]["isRestaurant"]}
dishid = {tagInfo[i]["Dish"]}
userid = {tagInfo[i]["Author"]}/>
);
}
this.recentCards = tempArray;
that.setState({loading:false});
调用
console.log(this.recentCards)
在 setState 显示数组中的项目之前。
但是,在此函数期间调用它不会返回任何项目:并且只有在加载设置为 false 时才会调用此函数。
showCards = () =>{
console.log(this.recentCards);
console.log(this.state.loading);
if(this.state.empty == true){
return(
<View style = {{flex:1, justifyContent:'center', alignItems:'center', backgroundColor:'#F7F6F4'}}>
<Text>{"No tag activity yet! You can start tagging on the Discover page!"}</Text>
</View>
);
}
else{
return(
<View style = {styles.contentContainer}>
{this.recentCards}
</View>
);
}
}
最佳答案
不能将{this.recentCards}
更改为this.state.recentCards
吗? this.recentCards 的值永远不会被“刷新”,因此它只会采用初始值。
在你的构造函数中:
this.state = {
..// state items
recentCards : <some initial value>
}
在你的函数中:
Promise.all(promises).then(function(results){
for(var i = 0; i < tagInfo.length; i++){
tempArray.push(
<FeedCard key = {(i + 1) * -1}
handleToUpdate = {this.addView}
mutual = {false}
time = {tagInfo[i]["Time"]}
restaurantid = {tagInfo[i]["Restaurant"]}
isRestaurant = {tagInfo[i]["isRestaurant"]}
dishid = {tagInfo[i]["Dish"]}
userid = {tagInfo[i]["Author"]}/>
);
}
that.setState({loading:false, recentCards : tempArray});
在你的渲染中:
showCards = () =>{
console.log(this.recentCards);
console.log(this.state.loading);
if(this.state.empty == true){
return(
<View style = {{flex:1, justifyContent:'center', alignItems:'center', backgroundColor:'#F7F6F4'}}>
<Text>{"No tag activity yet! You can start tagging on the Discover page!"}</Text>
</View>
);
}
else{
return(
<View style = {styles.contentContainer}>
{this.state.recentCards}
</View>
);
}
}
关于javascript - 使用组件变量来 react Native Promises 和 componentDidMount 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52366184/