[英]How to use DrawerLayoutAndroid component for building drawer in react-native apps?
[英]How to use variable within component inside function in react-native?
我正在從實時數據庫(firebase)中檢索一些數據,但是,當我嘗試在數據庫引用調用之外檢查“級別”的值時,我得到一個未定義的值,盡管它在引用中工作。
有沒有辦法允許訪問 react-native 組件內的變量“級別”?
我在網上看到了一些使用 this.setState 來實現此目的的示例,但在 function 中似乎沒有任何方法可以做到這一點。
function LevelsScreen() {
const reference = database()
.ref()
.once('value')
.then(snapshot => {
//get Levels from db
let levels = [];
snapshot.forEach((child) => {
levels.push(child.key);
})
console.log(levels);
});
return (
<SafeAreaView style={styles.categories}>
{/* Horizontal Scrollbox for Main Categories */}
<ScrollView horizontal={true} style={styles.scrollView}>
<View>
{/* This function should call LevelCard to return the components with the proper titles*/}
{levels.map(element => {
return (<LevelCard
level={element}/>)
})
}
</View>
</ScrollView>
</SafeAreaView>
);
}
function LevelsScreen() {
// use state so that the react can know when the update the screen.
const [levels, setLevels] = React.useState(null);
// upon the component mount, we call the database.
React.useEffect(() => {
database()
.ref()
.once("value")
.then((snapshot) => {
//get Levels from db
const levels = snapshot.map((child) => child.key);
// update the state so react knows to re-render the component
setLevels(levels);
});
}, []);
return (
<SafeAreaView style={styles.categories}>
{/* Horizontal Scrollbox for Main Categories */}
{levels ? (
<ScrollView horizontal={true} style={styles.scrollView}>
<View>
{/* This function should call LevelCard to return the components with the proper titles*/}
{levels.map((element) => {
return <LevelCard level={element} />;
})}
</View>
</ScrollView>
) : (
{/* show spinner when the levels is not got from the server */}
<ActivityIndicator />
)}
</SafeAreaView>
);
}
我認為如果您可以為此使用 Promises 會更好。
function LevelsFunction() {
return Promise(resolve=> {
database()
.ref()
.once('value')
.then(snapshot => {
const levels = [];
snapshot.forEach((child) => {
levels.push(child.key);
})
console.log(levels);
resolve(levels)
});
現在使用 async/await 或 then 從您想要的任何地方訪問 LevelsFunction。
前任:
componentDidMount(){
const levels = LevelsFunction().then(res => res);
console.log(levels);
}
或者
async componentDidMount(){
const levels = await LevelsFunction();
console.log(levels);
}
我強烈建議您不要在 class 渲染 function 中使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.