簡體   English   中英

React Native 解析響應 JSON 成 flatlist

[英]React Native parsing response JSON into a flatlist

我正在嘗試從以下 json 數據中解析響應 JSON :

{
  "location_id": 73,
  "location_name": "Aunt Mary's Great Coffee Shop",
  "location_town": "London",
  "latitude": 74.567,
  "longitude": 102.435,
  "photo_path": "http://cdn.coffida.com/images/78346822.jpg",
  "avg_overall_rating": 4.5,
  "avg_price_rating": 4.3,
  "avg_quality_rating": 4,
  "avg_clenliness_rating": 3.8,
  "location_reviews": [
    {
      "review_id": 643,
      "overall_rating": 4,
      "price_rating": 2,
      "quality_rating": 3,
      "clenliness_rating": 5,
      "review_body": "Great coffee, but the bathrooms stank!",
      "likes": 4654
    }
  ]
}

我正在嘗試解析來自 location_reviews 數組 object 的數據。 我已成功接收數據,因為我已在 console.log 中簽入

我還成功接收並在屏幕上打印了位置名稱和 ID

/* eslint-disable curly */
/* eslint-disable prettier/prettier */
/* eslint-disable react-native/no-inline-styles */
/* eslint-disable semi */
/* eslint-disable prettier/prettier */
    import React, {Component} from 'react';
    import {View, Text, ToastAndroid, FlatList, TouchableOpacity, StyleSheet} from 'react-native';

    class Location extends Component {
       constructor(props) {
        super(props);

        this.state = {
          locations: [],
          isLoading: true,
        };
      }

      getData = async () => {

        let loc_id = this.props.route.params.location_id;

        return await fetch(`http://10.0.2.2:3333/api/1.0.0/location/${loc_id}`, {
            method: 'get',
            'headers': {
                'Content-Type': 'application/json',
              },
            })
        .then((response) => {
              if (response.status === 200) {
                return response.json();
              } else if (response.status === 404) {
                ToastAndroid.show('Unable to locate location', ToastAndroid.SHORT);
              } else {
                throw 'something went wrong';
              }
            })
        .then((responseJson) => {

                const review = responseJson.location_reviews[0]
                console.log(review);

                this.setState({
                    locations: responseJson,
                    isLoading: false,
                  });

            })
        .catch((error) => {
              ToastAndroid.show(error.toString(), ToastAndroid.SHORT);
            });
      }

      renderItem = ({item, index}) => {
        let { locations } = item;

        if (!locations[0]) return null;
        let details = locations[0]

        return (
        <View>
            <View>
                <Text>{details.review_body}</Text>
                <Text>{details.review_id}</Text>
           </View>
        </View>
        );
      }

      keyExtractor = (item, index) => {
        return index.toString();
      }

      render() {
          return (
            <View style={styles.space}>
                  <TouchableOpacity
                  style={styles.space}
                    onPress = {() => this.getData()}
                  >
                          <View>
                              <Text>get data</Text>
                              <Text>Location id: {this.props.route.params.location_id}</Text>
                          </View>
                  </TouchableOpacity>

                  <View>
                    <Text style={styles.space}>{this.state.locations.location_name}</Text>
                    <Text style={styles.space}>{this.state.locations.location_town}</Text>
                  </View>

                  <View style={{flex: 1}}>
                      <FlatList
                        data={this.state.dataSource}
                        keyExtractor={this.keyExtractor}
                        renderItem={this.renderItem}
                      />
                  </View>

            </View>
              );
        }


   }

   const styles = StyleSheet.create({

    space: {
      margin: 20,
      padding: 20,
    },

   });

    export default Location;

但是我完全停留在如何訪問位置評論數據數組(review_id、review_body 等)

任何想法,將不勝感激

我設法讓平面列表使用以下方法進行編譯

  render() {
    if (this.state.isLoading) {
      return (
        <View>
          <Text>loading...</Text>
        </View>
      )
    } else return (
                  <View>
                      <Text>Name: {this.state.locations.location_name}</Text>
                      <FlatList
                        data={this.state.locations.location_reviews}
                        renderItem={({item}) => (
                          <View>
                              <Text>review id: {parseInt(item.review_id)}</Text>
                              <Text>body: {item.review_body}</Text>
                              <Text>overall rating: {parseInt(item.overall_rating)}</Text>
                              <Text>price rating: {parseInt(item.price_rating)}</Text>
                              <Text>quality rating: {parseInt(item.quality_rating)}</Text>
                              <Text>cleanliness rating: {parseInt(item.clenliness_rating)}</Text>
                          </View>
                        )}
                        keyExtractor={(item) => item.review_id.toString()}
                      />
                  </View>
          );
    }

請注意,您上面的 json_data 是 object, FlatList必須接收一個數組(然后,它會使用該數組中的每個項目調用renderItem ,並顯示此項目列表)。

您應該進行一些更改(我假設您希望FlatList顯示location_reviews數組中的項目列表):

  1. 在您的構造函數中,位置字段應為 object,最初為null
this.state = {
  location: null,
}
  
  1. 在您的渲染方法中,首先檢查this.state.location存在,如果不存在則不渲染任何內容或加載屏幕:
render() {
  const { location } = this.state;

  if (location === null) return null;
  ...
}
  1. 在您的渲染方法中,將this.state.location.location_reviews傳遞給您的FlatList
const { location } = this.state;

<FlatList
  data={location.location_reviews}
  ...
/>
  1. 最后,調整您的renderItem方法:
renderItem = ({item, index}) => {
  return (
    <View>
        <Text>{item.review_body}</Text>
        <Text>{item.review_id}</Text>
    </View>
  );
}

注意:我沒有對此進行測試,因為零食不起作用。 您可能還需要調整一些東西(即我更改了 this.state.locations -> this.state.location 等)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM