开发者问题收集

显示表 react-native-table-component 时出现未定义的 device.map 错误

2021-10-25
238

我正在开发一个 React Native 应用程序。我的要求是以表格格式显示来自 API 的数据。我正在使用 react-native-table-component。我无法遍历数组来显示表中的数据。下面是我的代码:

TargetSetUpPage.js:

import React, { useEffect } from "react";
import { StyleSheet, Text, Button, TextInput, ScrollView ,View} 
from "react-native";
import { useDispatch,useSelector } from "react-redux";
import * as authActions from "../../store/actions/auth";
import AsyncStorage from '@react-native- 
 community/asyncstorage';
 import { Table, Row, Rows } from 'react-native-table- 
 component';

  const TargetSetUpPage = (props) => {
  const [targetid, setTargetId] = React.useState("");
  const dispatch = useDispatch();
   const devices = [useSelector(state => 
  state.auth.availableDevice)];
  //console.log('The devices are: '+JSON.stringify(devices));

   if (typeof(devices) !== 'undefined' && devices != null) {
   console.log('Not Undefined and Not Null')
   } else {
   console.log('Undefined or Null')
   const devices = [useSelector(state => 
   state.auth.availableDevice)];

   }

   const tableHead = ['Target Id','Target Name']
   const tableRow = devices;
   console.log(devices); 
   const tableRows = (devices || []).map(item => ({ name: 
   item.name 
   }));


    useEffect(() => {
    const onScreenLoad = async() => {
    const useridfordevices = await 
     AsyncStorage.getItem("userDatauserid");
     const obj = JSON.parse(useridfordevices);
     const { userid } = obj;
     var userid1 = userid[0];
      await dispatch(authActions.getDeviceInfo(userid1))
     };
     onScreenLoad();
     },[dispatch]);

     return (
    <ScrollView showsVerticalScrollIndicator={true}>
    <View>
    {/* <Table borderStyle={{borderWidth: 2, borderColor: 
    '#c8e1ff'}}>
    <Row data={tableHead} style={styles.head} textStyle= 
     {styles.text}/>
    <Rows data={tableRows} textStyle={styles.text}/>
    </Table> */}
     <FlatList
     data={devices}
     keyExtractor={item => item.TargetId}
      renderItem={itemData => (
     <View style={styles.card}>
   
    {/* <Text style={styles.text}>{itemData.item.TargetName} 
    </Text> */}
    <Button title={itemData.item.TargetName} onPress={()=>{}}/>
    </View>
     )}
     numColumns={2}
      />

     <Text style={styles.headingTitle}>
     Set your target and start running:
     
    </Text>
    <Text style={styles.textstyle}>Target ID</Text>
    <TextInput
    style={styles.input}
    value={targetid}
    onChangeText={(targetid) => setTargetId(targetid)}
    ></TextInput>
    <Button
     title="Add"
     // onPress = {() => }
    />
    </View> 
    </ScrollView>
     );
     };

     const styles = StyleSheet.create({
     input: {
     height: 40,
     width: "80%",
     margin: 12,
     borderWidth: 1,
     padding: 10,
     },
     headingTitle: {
     fontSize: 30,
      },
      textstyle: {
       paddingTop: 10,
       fontSize: 20,
        },
      compact: {
      flexDirection: "row",
       },});

      export default TargetSetUpPage;

执行后,它在控制台中显示以下 tableRow 数组:

非未定义且非空 数组 [ undefined, ]

TypeError:undefined 不是对象(评估“item.name”)

但是如果我删除表并显示 FlatList,我能够毫无问题地显示列表。我不知道我在显示表时犯了什么错误。提前致谢。

2个回答
// devices will be the same as auth.availableDevice in your redux
  // If auth.availableDevice is undefined at any point, like during boot
  // then devices will be undefined too
  const devices = useSelector(state => state.auth.availableDevice);

  // Let's write our map code so that it handles the case where devices is undefined
  const tableRows = (devices || []).map(item => ({ name: item.name }));
windowsill
2021-10-26

我使用了 react-native-paper 中的 DataTable 来获取表格。下面是从 API 渲染数据的代码。

TargetSetUpPage.js:

import React, {useEffect} from "react";
import {StyleSheet, Text, Button, TextInput, ScrollView, View, FlatList}
    from "react-native";
import {useDispatch, useSelector} from "react-redux";
import * as authActions from "../../store/actions/auth";
import AsyncStorage from '@react-native-community/async-storage';
import {DataTable} from 'react-native-paper';

const TargetSetUpPage = (props) => {
    const [targetid, setTargetId] = React.useState("");
    const dispatch = useDispatch();
    const devices = useSelector(state => state.auth.availableDevice);

    useEffect(() => {
        const onScreenLoad = async () => {
            const useridfordevices = await
                AsyncStorage.getItem("userDatauserid");
            const obj = JSON.parse(useridfordevices);
            const {userid} = obj;
            var userid1 = userid[0];
            await dispatch(authActions.getDeviceInfo(userid1))
        };
        onScreenLoad();
    }, [dispatch]);

    return (
        <ScrollView showsVerticalScrollIndicator={true}>
            <View>
                <DataTable>
                    <DataTable.Header>
                        <DataTable.Title>
                            <Text>Target Id</Text>
                        </DataTable.Title>
                        <DataTable.Title>
                            <Text>Target Name</Text>
                        </DataTable.Title>
                    </DataTable.Header>
                    {devices.map((item, key) => (
                            <DataTable.Row>
                                <DataTable.Cell>{item.TargetId}</DataTable.Cell>
                                <DataTable.Cell>{item.TargetName}</DataTable.Cell>

                            </DataTable.Row>
                        )
                    )}
                </DataTable>
                <Text style={styles.headingTitle}>
                    Set your target and start running:
                </Text>
                <Text style={styles.textstyle}>Target ID</Text>
                <TextInput
                    style={styles.input}
                    value={targetid}
                    onChangeText={(targetid) => setTargetId(targetid)}
                ></TextInput>
                <Button title="Add"
                    // onPress = {() => }
                />
            </View>
        </ScrollView>
    );
};

const styles = StyleSheet.create({
    input: {
        height: 40,
        width: "80%",
        margin: 12,
        borderWidth: 1,
        padding: 10,
    },
    headingTitle: {
        fontSize: 30,
    },
    textstyle: {
        paddingTop: 10,
        fontSize: 20,
    },
    compact: {
        flexDirection: "row",
    },
});

export default TargetSetUpPage;

它在屏幕上显示表格,如下所示。

来自 API 数据的表格

Poornima Gurudath
2021-10-28