ReactNative-从promise(JSON)获取数据



我能够获取JSON数据,它现在返回一个数组。如何在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,我只会在获取函数中执行所有逻辑,对我来说,如果你得到一个数组,它是用于几个元素的,所以我会用映射方法来准备它

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;

最新更新