【问题标题】:React Native Fetch API get method for response JSONReact Native Fetch API 获取响应 JSON 的方法
【发布时间】:2021-03-05 22:09:51
【问题描述】:

我正在尝试访问以下 API 端点:

[
  {
    "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
      }
    ]
  }
]

使用以下 Fetch 请求:

  getsearchData = async () => {
    const value =  await AsyncStorage.getItem('@session_token');
    return fetch('http://10.0.2.2:3333/api/1.0.0/find/', {
      headers: {
        'X-Authorization': value,
      },
    })
      .then((response) => {
        if (response.status === 200) {
          return response.json();
        } else if (response.status === 401) {
          ToastAndroid.show('Your not logged in', ToastAndroid.SHORT);
        } else {
          throw 'something went wrong';
        }
      })
      .then((responseJson) => {
        //setIsLoading(false);
        this.setState({
            isLoading: false,
            locations: responseJson,
        });
      })
      .catch((error) => {
        console.log(error);
      });
  };

我可以像这样访问第一个对象:

<Text>ID: {parseInt(item.location_id)}</Text>

但是,如果我想访问总体评级或评论机构,我不知道该怎么做?

 <Text>Review ID: {item.review_location_id}</Text>

【问题讨论】:

    标签: react-native networking fetch


    【解决方案1】:

    假设您在数据上使用了 map 方法来呈现它并访问属性值,您可以使用相同的语法来访问其他属性,但是如果您想访问对象属性值的嵌套数组,我的意思是“location_reviews " 或将来的任何其他内容,您还需要映射该道具,因为它是包含对象的数组。
    假设您的代码如下所示:

    {data.map(item => (<Text>ID: {parseInt(item.location_id)}</Text>)}
    
    to access location_reviews.review_id for example, you have to map on internal array 
    as well
    
    {data.map(item => (<Text>{item.location_reviews.map(item => item.review_id)}</Text>))}
    

    我为你制作了零食让你玩得更开心snack

    【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    相关资源
    最近更新 更多