我有一个带有主 node "user"的实时数据库,在其中我有3个子 node ,这3个子 node 又有4个子 node ,每个子 node .4个 node 中的一个是录音,一个是图像,其中两个是字符串.我试图用"下一步"和"上一步"按钮动态地获取它们,按下"下一步"时,屏幕上会显示下一个 node 的数据.
我使用useState动态更改数据库(ref)的路径,但按下next/back按钮时,屏幕上的数据不会更新.后来我发现,当我刷新/重写ref()时,按下next/back按钮.在功能上,我的数据会得到更新,但我必须为每家媒体做这件事.
这是我的apply.js代码:
import Sound from 'react-native-sound';
import database from '@react-native-firebase/database';
import storage from '@react-native-firebase/storage';
import React , {useEffect, useState} from 'react';
import {
ScrollView,
StyleSheet,
Alert,
Text,
View,
Image,
Button
} from 'react-native';
const App = () => {
const [myData,setData] = useState({
letter:'',
pronun:'',
word:'',
image:''
});
const [img,setimg] = useState(null);
const [pronunn,setpronun] = useState(null);
const [hey,sethey] = useState(1);
useEffect(() => {
getDatabase();
}, []);
function getDatabase() {
database().ref('users/'+hey+'/').on('value' , (snapshot) => {
Sound.setCategory('Playback', true);
var poo=new Sound(snapshot.val().pronun);
setData({
letter: snapshot.val().letter,
word: snapshot.val().word,
image: setimg(snapshot.val().image),
pronun: setpronun(poo)
});
console.log(snapshot.val());
});
}
return (
<View style={{flex:1, backgroundColor:'#000000', alignContent:'center', alignItems:'center', justifyContent:'center'}}>
<ScrollView>
<Text style={{color:'#ffff'}}>
Letter: {myData ? myData.letter : 'loading...' }
</Text>
<Text style={{color:'#ffff'}}>
Word: {myData ? myData.word : 'loading...' }
</Text>
<Image style={{width:200, height:200}}
source={{uri: img}}
/>
<View>
<Button
title='Pronunciation'
onPress={() => {
return pronunn.play();
}}
>
</Button>
<Button title='Next' onPress={
() => {
if (hey>2) {
Alert.alert('no more records');
}
else {
return sethey(hey+1);
}
}
}
>
</Button>
<Button title='back' onPress={
() => {
if (hey<2) {
Alert.alert('no more records to go back');
}
else {
return sethey(hey-1);
}
}
}
>
</Button>
</View>
</ScrollView>
</View>
);
};
export default App;