React Native - 从 promise 获取数据 (JSON)

ReactNative - get data from promise (JSON)

我能够获取 JSON 数据,它现在 returns 是一个数组。如何在 React Native 中使用数组中的元素?以下是我的尝试:

export default function display() {

const fetching = async() => ... //defines fetching() which returns the array

...

    return (
       <View>
           <Image 
                source = {{uri: 'http://imageURI.' + fetching().then((arr) =>  {return arr[0]}) + '.png'}}
                style = {{height: 50, width: 50, borderRadius: 50}} />
       </View>
    )

}

如何访问数组中的元素?

试试下面的方法。

您需要异步进行 API 调用,显示一些内容直到获得响应,然后使用检索到的数据更新状态。

import React, {useState, useEffect} from 'react';
import {View, Image} from 'react-native'

const fetch = async () => {/* ASYNC LOGIC HERE*/};

const MyComponent = () => {
  const [uri, setUri] = useState(null);

  useEffect(() => {
    fetch().then((arr) => {
      setUri(`http://imageURI.${arr[0]}.png`);
    });
  }, []);

  return (
    <View>
      {
        uri ? <Image source={{uri}} style={{height: 50, width: 50, borderRadius: 50}} /> : null
      }
    </View>
  );
};

我同意 ernesto 的观点,我会在获取函数中完成我的所有逻辑,对我来说,如果你得到一个数组,它是针对几个元素的,所以我会用 map 方法准备它

import React, { useState, useEffect } from "react";
import { View, Image } from "react-native";

const Display = () => {
 const [state, setState] = useState(null);

 const fetching = async () => {
  try {
   const response = await fetch("api.exemple");
   const imagesArray = await response.json();

   setState(imagesArray);
  } catch (error) {
   console.log(error);
  }
 };

 useEffect(() => {
  fetching();
 }, []);

 return (
  <View>
   {state &&
    state.map((fileName) => {
     const uri = `http://imageURI.${fileName}.png`;
     return (
      <Image
       source={{ uri }}
       style={{ height: 50, width: 50, borderRadius: 50 }}
      />
     );
    })}
   </View>
 );
};

export default Display;