首页 > 解决方案 > 嵌套标签未出现在 React Native App 中

问题描述

我正在尝试使用 Javascript 有条件地在 React Native 应用程序上呈现一些文本,但由于某种原因它没有出现。

下面是我的代码:

import React from 'react';
import { StyleSheet, Text, View, TextInput } from 'react-native';
import firebase from '../firebase/firestore';


class FormBuilder extends React.Component {
    constructor() {
        super();
        this.firestoreRef = firebase.firestore().collection('Forms');
        this.state = {
          isLoading: true,
          formArr: []
        };
      }

    componentDidMount() {
        this.unsubscribe = this.firestoreRef.onSnapshot(this.getCollection);
    }

    componentWillUnmount(){
        this.unsubscribe();
    }



    getCollection = (querySnapshot) => {
        const formArr = [];
        querySnapshot.forEach((res) => {
          const { FormId, Company, CreatedBy, CreatedWhen, LastModified, LastModifiedBy, Payload } = res.data().formMetaData;
          formArr.push({
            FormId: FormId,
            Company: Company,
            CreatedBy: CreatedBy,
            CreatedWhen: CreatedWhen,
            LastModified: LastModified,
            LastModifiedBy: LastModifiedBy, 
            Payload: Payload
          });
        });
        this.setState({
            formArr,
          isLoading: false,
       });
    }

    render() {
        if (this.state.isLoading){
          return(
            <View style={styles.preloader}>
              <Text>Loading...</Text>
            </View>
          )
        }
        return(
            <View style={styles.dumb}>
                <Text>Form Data Below</Text>
                <View>
                    <Text>{
                        this.state.formArr.length > 0 ? this.state.formArr.map((item) => {
                            
                            <Text>Hello</Text>
                            

                        }) : <Text>No Forms in Database</Text>
                    
                    }</Text>
                </View>

            </View>
        )
    }
}


const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingBottom: 0
    },
    preloader: {
        paddingTop: 10,
        alignItems: 'center',
        justifyContent: 'center'
    },
    dumb: {
        borderWidth: 1,
    }

  })
  
  export default FormBuilder;

因此,我正在从数据库接收数据,并在加载数据后显示该数据。我遇到问题的部分是这一行:

{this.state.formArr.length > 0 ? this.state.formArr.map((item) => {
   <Text>Hello</Text>

 }) : <Text>No Forms in Database</Text>
}

即使this.state.formArr.length > 0达到条件,<Text>Hello</Text>也不会出现在屏幕上。

我检查了是否达到了条件,因为如果我替换<Text>Hello</Text>alert(1),则会出现警报。

屏幕上唯一的东西是<Text>Form Data Below</Text>

我错过了一些明显的东西吗?我知道条件正在执行,那为什么<Text>标签不渲染?让我知道你们是否有任何问题。

标签: javascriptreact-native

解决方案


我在您的代码中看到的问题是,在映射一个数组后,您没有返回一个组件,这就是它没有在屏幕上显示任何内容的原因。

试试这个

{
  this.state.formArr.length > 0 ? (
    this.state.formArr.map(item => {
      return <Text>Hello</Text>;
    })
  ) : (
    <Text>No Forms in Database</Text>
  );
}

推荐阅读