在本机中呈现数据之前执行异步调用

问题描述 投票:0回答:1

渲染数据后我的异步调用正在运行我尝试在构造函数中运行我的异步调用,甚至在componentDidMount内部但没有任何效果。

我的数据库结构..

Firebase Real time database

我在jsx文件中的查询

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

问题是我想根据我的react本机app中的数据库中的数据加载图像。

<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函数

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]
    });     
}

如果你想了解更多细节,请告诉我。

javascript react-native firebase-realtime-database jsx
1个回答
1
投票

您可以通过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>
© www.soinside.com 2019 - 2024. All rights reserved.