【发布时间】:2019-04-11 09:07:01
【问题描述】:
当您单击分页按钮时,以下代码将针对未处理的 Promise 拒绝 'cannot read property 'lastVisiblePost' of undefined 返回错误。
它似乎在执行初始 getPosts 之后立即将状态设置为 null。
它在第一次运行时有效,但是当您点击调用getPosts 状态的按钮时将等于null。
class App extends Component {
state = {
listState: 'top',
allPosts: [],
lastVisiblePost: null
}
async componentDidMount() {
const { user } = await firebase.auth().signInAnonymously()
this.getPosts()
}
async getPosts() {
console.log(this.state)
console.log(this.state.lastVisiblePost)
let posts = null
if (this.state.lastVisiblePost) {
posts = await firebase.firestore()
.collection('posts')
.orderBy('likes')
.startAfter(last)
.limit(2)
.get()
} else {
posts = await firebase.firestore()
.collection('posts')
.orderBy('likes')
.limit(2)
.get()
}
let newPosts = []
posts.forEach(post => {
newPosts.push({
id: post.id,
data: post.data()
})
})
console.log(posts.docs)
console.log("memes", posts.docs[posts.docs.length - 1])
this.setState({
allPosts: newPosts,
lastVisiblePost: posts.docs[posts.docs.length - 1]
}, () => {
console.log("doink", this.state)
})
}
render() {
const { listState, allPosts } = this.state
return (
<SafeAreaView style={styles.container}>
{ /* Logo */ }
<View style={styles.logoContainer}>
<Image style={styles.logo} source={anywayLogo} />
</View>
{ /* Top and New Buttons */ }
<View style={styles.topAndNewContainer}>
<Text style={[styles.topAndNewText, listState === 'top' ? { color: 'red' } : { color: 'black' }]} onPress={() => this.setState({listState: 'top'})}>top</Text>
<Text style={[styles.topAndNewText, listState === 'new' ? { color: 'red' } : { color: 'black' }]} onPress={() => this.setState({listState: 'new'})}>new</Text>
</View>
{ /* Feed */ }
<View style={styles.feedContainer}>
{
allPosts.map(post => {
return (<Text key={post.id}>{post.data.title}</Text>)
})
}
</View>
<Button title="Next page" onPress={this.getPosts} />
</SafeAreaView>
);
}
}
async await 会破坏我的状态吗?
【问题讨论】:
标签: javascript reactjs react-native asynchronous async-await