【问题标题】:REACT NATIVE: How to fetch API JSON data in RNREACT NATIVE:如何在 RN 中获取 API JSON 数据
【发布时间】:2021-02-12 14:42:01
【问题描述】:

我正在尝试从此 API 获取 JSON 数据:'https://dog.ceo/api/breeds/list/all' 我什至从官方文档中尝试过几次,但没有任何帮助,我没有收到错误,但屏幕上显示了 nthing

 useEffect(() => {
    fetch('https://dog.ceo/api/breeds/list/all')
      .then((response) => response.json())
      .then((json) => setData(json.message))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

   
  return (
    <View style={{ flex: 1, padding: 24 }}>
      {isLoading ? <ActivityIndicator/> : (
        <FlatList
          data={data}
          keyExtractor={({ id }, index) => id}
          renderItem={({ item }) => (
            <Text>{item.message}  ghbdt </Text>
                      )}
        />
      )}
    </View>

【问题讨论】:

    标签: json reactjs react-native api


    【解决方案1】:

    您可以尝试使用 async 并在事件单击时调用 handleData 或使用 useEffect 。希望这种方式对您有所帮助。

    async handleData() {
    axios.get('https://dog.ceo/api/breeds/list/all')
      .then((response) => response.json())
      .then((json) => setData(json.message))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
      }
    

    另一种方式也许你可以尝试在数组依赖useEffect[]中传递数据。

    【讨论】:

    • 对不起,我应该把它放在哪里??
    【解决方案2】:

    您遇到的问题是 API 的返回是对象而不是数组:

    {"message":{"affenpinscher":[],"african":[],"airedale":[]...}}

    为了使这项工作为您工作,您需要将返回的数据转换为数组,如果您所追求的只是键值而不是数组中的值,那么您只需将您的 setData 更改为 @987654323 @这会给你一个狗的名单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 2021-10-19
      • 1970-01-01
      • 2021-12-23
      相关资源
      最近更新 更多