如何解决如何在本机函数内部的组件内使用变量?
我正在从实时数据库(firebase)中检索一些数据,但是,当我尝试在数据库引用调用之外检查“级别”的值时,尽管它在引用中起作用,但我还是得到了一个未定义的值。
有没有办法允许访问反应本地组件内部的变量“级别”?
我在网上看到了一些使用this.setState来实现此目的的示例,但是似乎没有任何方法可以在函数中执行此操作。
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>
);
}
解决方法
- 您应该使用 state 使反应知道要渲染的内容。
- 从数据库中获取数据时,我们将更新状态。
- 更新状态会触发React中的重新渲染,这表示React会在屏幕上渲染新内容。
- 然后,您可以向用户显示您的新状态。
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或之后的方式从所需的任何位置访问LevelsFunction。
例如:
componentDidMount(){
const levels = LevelsFunction().then(res => res);
console.log(levels);
}
或
async componentDidMount(){
const levels = await LevelsFunction();
console.log(levels);
}
我强烈建议您不要在类渲染函数中使用它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。