【问题标题】:Do async call before rendering data in react native在本机反应中渲染数据之前进行异步调用
【发布时间】:2018-08-09 08:27:06
【问题描述】:

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

我的数据库结构..

我在 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 native 应用程序中的数据库中的数据加载图像。

<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】:

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

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

    【讨论】:

      【解决方案2】:

      您可以通过 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>
      

      【讨论】:

      • 我想跟踪 6 个组件检查我的问题中的 cmets
      • 编写一个具有通过状态更新图像源的功能的子组件。为此设置参考。异步完成后,调用此更新函数来更新您的子图像数据
      • 有什么方法可以在数据加载之前不渲染任何东西?
      • 我认为这不是一个好主意,要做到这一点,本质上你必须锁定 JS 线程。你知道,一个 React Native 应用程序只有一个 JS 线程。您可以通过在渲染中返回 null 来“不渲染”(您的异步尚未准备好)
      猜你喜欢
      • 2021-09-26
      • 2018-04-05
      • 2018-12-22
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      相关资源
      最近更新 更多