我在找一个firebase实时数据库。 我可以用console.log()显示数据,但不能用平面列表显示。 我尝试了不同的方法来解决这个问题。 但是,我找不到任何确切的解决办法。 这里,我在FireBase中的JSON树:
这里是我的代码:
const NotesList = (props) => {
const { colors } = useTheme();
const styles = customStyles(colors);
const user = auth().currentUser
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const getData = () => {
firebase.database().ref(`notes/`).on('value', function (snapshot) {
console.log(snapshot.val())
});
}
useEffect(() => {
setTimeout(() => {
setData(getData);
setLoading(true);
}, 1000);
}, []);
const renderItem = ({ item }) => {
return (
<View style={{ marginRight: 10, marginLeft: 10 }}>
<TouchableOpacity>
<NoteCard title={item.noteTitle} icerik={item.noteDetails} date={item.timestamp} />
</TouchableOpacity>
</View>
);
};
const split = () => {
let icerik = data.map((item, key) => item.icerik);
return icerik.slice(0, 1) + '...';
};
return (
<View style={styles.container}>
<StatusBar barStyle="light-content" />
<NoteSearchBar />
{!loading ? (
<View style={{ alignItems: 'center' }}>
<ActivityIndicator color="#ff5227" />
</View>
) : (
<FlatList
data={data}
numColumns={2}
renderItem={renderItem}
keyExtractor={(item, index) => index.toString()}
/>
)}
<TouchableOpacity
style={styles.addButton}
onPress={() => props.navigation.navigate('AddNote')}>
<Plus width={40} height={40} fill="white" margin={10} />
</TouchableOpacity>
</View>
);
};
我尝试了许多不同的方法,但没有任何建议解决了这个问题。 如果你能帮忙我会很高兴的。
您的GetData
不返回数据,因为数据是异步加载的。 您应该将对setdata
的调用移到您的getdata
:
const getData = () => {
firebase.database().ref(`notes/`).on('value', function (snapshot) {
setData(snapshot.val());
});
}
useEffect(() => {
setTimeout(() => {
getData()
setLoading(true);
}, 1000);
}, []);
现在,对setdata
的调用将使JSON进入状态,这反过来迫使React使用新数据重新绘制UI。
再见,基本上你犯了两个错误:
GetData
不返回任何内容,因此永远不会用来自FireBase的值更新数据;UseEffect
有一个奇怪的实现(调用SetTimeout
没有用,您已经在等待来自firebase的数据);我的建议是从UseEffect
中调用GetData
:
useEffect(() => {
getData()
}, []);
并按如下方式修改getdata
:
const getData = () => {
firebase.database().ref(`notes/`).on('value', function (snapshot) {
setData(snapshot.val());
setLoading(true);
});
}