我使用 firebase 调用一些用户数据,并将其存储在一个数组中。然后,当我定义状态时,我将“noteData”设置为该数组。但是,构造函数中的 console.log(this.state.noteData) 返回“Array[]”,返回方法不显示映射组件系列。
我创建了一个运行 this.forceUpdate() 然后运行 console.log(this.state.noteData) 的按钮,这会导致所有组件正确呈现,并且 console.log() 返回它应该的数组。
我尝试使用 .bind(this) 和 componentWillMounth(),但我不知道如何确保在渲染方法第一次运行之前定义状态。
似乎渲染在状态更新之前就在运行,只有在按下按钮后重新渲染才能修复它。此外,我可以在加载到此屏幕后立即多次按下 forceUpdate() 按钮,直到几秒钟后才会发生任何事情。我的猜测是数据在此期间仍在更新。
constructor(props){
super(props);
let returnArr = [];
firebase
.database()
.ref('/users/' + firebase.auth().currentUser.uid + '/notes')
.once('value')
.then(snapshot => {
snapshot.forEach(childSnapshot => {
let item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
})
})
this.state = {
fontPreference: firebase.auth().currentUser.fontPref,
noteData: returnArr
}
console.log(this.state.noteData);
}
/* * * forceUpdate() button * * */
<TouchableOpacity
onPress={() => {
this.forceUpdate();
console.log(this.state.noteData)
}}>
...
/* * * within return method of render * * */
<ScrollView>
{this.state.noteData.map(note => {
return <NotePreview
navigation = {this.props.navigation}
currNoteImg={note.noteImg}
currNoteTxt={note.noteTxt}
noteId={note.key}
/>
})}
</ScrollView>
最佳答案
只需在 .then
中使用 setState 即可
constructor(props){
super(props);
let returnArr = [];
// declare default state
this.state = {
fontPreference: firebase.auth().currentUser.fontPref,
noteData: []
}
firebase
.database()
.ref('/users/' + firebase.auth().currentUser.uid + '/notes')
.once('value')
.then(snapshot => {
snapshot.forEach(childSnapshot => {
let item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
})
// update state
this.setState({
noteData: returnArr
})
})
}
关于javascript - 构造函数中的变量在渲染前未定义但在渲染后可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57406787/