繁体   English   中英

在 React Native 中渲染数据之前执行异步调用

[英]Do async call before rendering data in react native

我的 Asyc 调用在数据呈现后运行我尝试在构造函数中甚至在 componentDidMount 中运行我的 Asyc 调用,但没有任何效果。

我的数据库结构..

Firebase 实时数据库

我在 jsx 文件中的查询

for(var i = 1; i <= 6; i++) {
    Firebase.database().ref('/' + i).on('value', function(snapshot) {
        value[i] = snapshot.val().state;
    });
}
console.log(value);

问题是我想根据我的本机应用程序内的数据库中的数据加载图像。

<View style={styles.container}>
  <View style={styles.parent}>
    // This is only one child
    <TouchableOpacity style={styles.child} id='1' onPress={(event) => this.getState(event, '1')} activeOpacity={1}>
      <Image style={styles.img} source={value[1]} /> // This line is not outputting any image because the array is empty
      <Text style={styles.title}>LED 1</Text>
    </TouchableOpacity>
    // I have 6 child and want to keep the states separate for all
</View>

获取状态函数

getState (event, BtnId) {
    value[BtnId] = this.state.mode_1 ? require('./img/on.png') : require('./img/off.png')
    Firebase.database().ref(BtnId).update({
        'state': value[BtnId]
    });     
}

如果您想了解更多详细信息,请告诉我。

您可以通过setState简化解析。

async componentDidMount () {
const imageUrl = await yourAsyncProcess()
this.setState({imageUrl: imageUrl})
}

并使用更新后的状态进行渲染

<View style={styles.container}>
  <View style={styles.parent}>
    <TouchableOpacity style={styles.child} id='1' onPress={(event) => this.getState(event, '1')} activeOpacity={1}>
      <Image style={styles.img} source={uri: {this.state.imageUrl}} /> // This line is not outputting any image because the array is empty
      <Text style={styles.title}>LED 1</Text>
    </TouchableOpacity>
</View>

不建议在渲染前进行异步调用,因此正确的方法是在componentDidMount启动异步调用,并使用本地状态的标志来运行微调器或加载指示器,直到异步调用解析或拒绝。

对于 React 钩子,在React.useEffect执行异步调用,并以类似的方式切换本地状态钩子的值以有条件地呈现微调器或数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM