【问题标题】:ReactNative - get data from promise (JSON)React Native - 从 Promise (JSON) 获取数据
【发布时间】:2023-03-18 10:35:02
【问题描述】:

我能够获取 JSON 数据,它现在返回一个数组。如何在本机反应中使用数组中的元素?以下是我的尝试:

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>
    )

}

如何访问数组中的元素?

【问题讨论】:

  • 你能把你的fetchingmehtod 的完整代码贴出来吗?

标签: javascript reactjs react-native fetch async.js


【解决方案1】:

试试下面的。

您需要使您的 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>
  );
};

【讨论】:

  • 非常感谢,这真的很有帮助,但我对 RN 还是很陌生,请问 UseEffect 什么时候真正运行?为什么当我在 useEffect 中的 console.log(uri) 给出 null 时,它在下面的 return 语句中起作用?
  • @cel-0207 useEffect 钩子(参见here)在组件“挂载”后立即运行(在将具有初始状态的元素添加到 DOM 之后),然后在每个组件上再次运行仅当依赖项数组中的至少一个变量(第二个参数)发生更改时才呈现。
  • @cel-0207 设置状态(在这种情况下使用setUri)有时可能会异步发生。当useEffect 第一次运行时,您在调用setUri 之后读取null,也可能在之后立即运行。一旦状态有效改变,就会触发重新渲染,您会在 return 语句中读取新值。
  • @cel-0207 在这种情况下,由于依赖项数组为空,useEffect 将只运行一次!
【解决方案2】:

我同意 ernesto 的观点,我会在 fetching 函数中完成我所有的逻辑,对我来说,如果你得到一个数组,它是针对几个元素的,所以我会用 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;

【讨论】:

  • 非常感谢您的帮助,map方法在这里真的很有必要:)!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-25
  • 2015-07-15
  • 2021-10-19
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
相关资源
最近更新 更多