首页 > 解决方案 > 如何将 API 数据获取到 Text Element React Native

问题描述

我已成功完成 API 调用并将数据放入对象中。现在我想将 API 数据放入TEXT元素中。以下是我的代码和数据数组。我想在文本元素中显示 createdAt 和任务。任何建议都会有很大帮助。提前致谢

            (async () => {
            try{
            let ServiceTicketData = await fetch(`${API_URL}/v1/serviceTicket`, {
                method: 'GET',
                headers: {
                    Accept: 'application/json',
                    'apiKey': 'asdkhjfgsed34e',
                    'deviceId': deviceId,
                    'sessionId': sessionId
        
                },
            });
            let STData = await ServiceTicketData.json();
            console.log("ST Data",STData);
            setServiceTData(STData);
            setRefreshing(false)
            } catch (error) {
                console.log(error);
            }
        })()
            
        }, [refreshing]);
        
console.log("Newdata",ServiceTData);

我的数据数组:

Newdata Object {
  "data": Object {
    "createdAt": "2021-08-06 13:27:55",
    "tasks": Array [
      Object {
        "completed": false,
        "createdAt": null,
        "model": "Lexmark:MS510DN",
        "product": "PRINTER",
        "remark": "paper jam",
        "serialNumber": "451444HH1N1GT",
        "status": null,
        "topic": "21080295T210",
        "ttId": 27226,
        "warrantyStatus": "MAINTENANCE_COMPREHENSIVE",
      },
    ],
    "topic": null,
    "visitingAdd1": "J/ HARTLEY COLLEGE,",
    "visitingAdd2": "POINT PEDRO",
    "visitingAdd3": "POINT PEDRO",
  },
  "errorCode": null,
  "reason": "Successful",
  "success": true,
}

现在我想将数据放入以下

function RenderServiceTicket(ServiceTData){
    return ( 
    <SafeAreaView>
      <ScrollView style={{paddingTop: 10}}>
        <Card borderRadius={15} >
        <View>
            <Text>{ServiceTData.createdAt}</Text>
            <Text>{ServiceTData.tasks}</Text> <=== "*This should be in a List*"
        </View>
    </Card>
    </ScrollView>
    </SafeAreaView>
    );
}

标签: react-native

解决方案


tasksinServiceTDataArray一个. 您可以使用该FlatList组件来呈现您的列表。

代替

<Text>{ServiceTData.tasks}</Text> <=== "*This should be in a List*"

<FlatList
  data={ServiceTData?.data?.tasks || []}
  renderItem={({item}) =>
    // the flatlist will loop over your tasks array and you can access each 
    // element as item.
    (
      <View>
       <Text>{item?.model ?? ''}</Text>
       // display the data you want to show like above

       <Text>{item?.createdAt ??''}</Text> // added createdAt as said in comments. You can access all the values with the same approach.
      </View>
    )
  }
  keyExtractor={(item) => item. ttId}
/>

你可以阅读更多关于FlatListFlatList React Native

Optional Chaining从您的问题的回复中添加, createdAt 在 one 中为 null task object。可选的链接将防止您的应用程序崩溃。

您可以将RenderServiceTicket功能更改为

function RenderServiceTicket(ServiceTData){
  return ( 
    <SafeAreaView>
      <ScrollView style={{paddingTop: 10}}>
        <Card borderRadius={15} >
          <View>
            <Text>{ServiceTData?.data?.createdAt ?? '' }</Text>
            <FlatList
              data={ServiceTData?.data?.tasks || []}
              renderItem={({item}) =>
                // the flatlist will loop over your tasks array and you can access each 
                // element as item.
               (
                 <View>
                   <Text>{item?.model ?? ''}</Text>
                   // display the data you want to show like above

                   <Text>{item?.createdAt ??''}</Text> // added createdAt as said in comments. You can access all the values with the same approach.
                  </View>
                )
              }
              keyExtractor={(item) => item. ttId}
            />
          </View>
        </Card>
      </ScrollView>
    </SafeAreaView>
  );
}

添加现场小吃


推荐阅读