我有一个带有主节点“用户”的实时数据库,然后在其中我有 3 个子节点,这 3 个子节点还有 4 个子节点,每个子节点都是。 4个节点之一是录音,1个是图像,其中2个是字符串。我尝试使用“下一步”和“后退”按钮动态获取它们,按下“下一步”后,下一个节点的数据将显示在屏幕上。
我正在使用 useState 来动态更改数据库的路径(引用),但是按下一步/后退按钮时,屏幕上的数据不会更新。后来我发现,当我刷新/重写 ref().on 函数时,按下下一步/后退按钮后,我的数据会更新,但每次按下时我都必须执行此操作。
这是我的 App.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;
最佳答案
由于您的 setData
钩子(Hook)/效果取决于 hey
状态,因此您需要在 useEffect
中将后者指定为数据的依赖项正在加载。
useEffect(() => {
getDatabase();
}, [hey]);
另请参阅:
- 关于
useEffect
的文档,特别是有关依赖项的部分。 - setState in React's useEffect dependency array
关于javascript - firebase 实时数据库未在 native react 中使用 onPress 获取,每次都必须刷新 ref().on 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71818317/