简体   繁体   English

React Native - 使用 useState 传递 API 响应数据的问题

[英]React Native - problem with passing API response data using useState

I am trying to understand why my API response data is not showing up.我试图了解为什么我的 API 响应数据没有显示出来。 I have tested with console.log that my response data is actually correct.我已经用 console.log 测试过我的响应数据实际上是正确的。

In my TopCryptoList.js component I am trying to show data on flatlist according to my API call response data.在我的 TopCryptoList.js 组件中,我试图根据我的 API 调用响应数据在 flatlist 上显示数据。 The results data is supposed to be coming from useResults.js file where the API call happens.结果数据应该来自发生 API 调用的 useResults.js 文件。 For some reason I can't get the "results" data from useResults.js to my TopCryptoList.js component.出于某种原因,我无法从 useResults.js 获取“结果”数据到我的 TopCryptoList.js 组件。

Am I missing here something obvious?我在这里错过了一些明显的东西吗? I am just learning to use React and states and hooks.我只是在学习使用 React、状态和钩子。 When I console.log(response.data) in the useResults.js just after the axios.get call I get the correct JSON response data.当我在 axios.get 调用之后在 useResults.js 中使用 console.log(response.data) 时,我得到了正确的 JSON 响应数据。 However when I console.log(results) in my TopCryptoList I get empty object and therefore Flatlist can't render anything visible.但是,当我在 TopCryptoList 中使用 console.log(results) 时,我得到空对象,因此 Flatlist 无法呈现任何可见内容。

TopCryptoList.js: TopCryptoList.js:

import React from 'react';
import { View, Text, FlatList, StyleSheet, TextBase } from 'react-native';
import { createAppContainer } from 'react-navigation';
import useResults from '../hooks/useResults';

const TopCryptoList = ( ) => {

    const [searchCrypto, results] = useResults();

    console.log("THIS WE HAVE: " + results);

    return (
        <View style={styles.container}>
            <FlatList
                showsVerticalScrollIndicator={false}
                data={ results }
                keyExtractor={( result ) => result.id}
                renderItem={({ result }) => {
                    return (
                        <Text style={styles.item}>{result.name}</Text>
                    );
                }}
            />
        </View>
    )  
}

useResults.js:使用Results.js:

import { useEffect, useState } from 'react';
import axios from 'axios';

export default () => {

const [results, setResults] = useState([]);

const options = {
    method: 'GET',
    params: {
        'id': '1,2'
    },
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json;charset=UTF-8',
        'X-CMC_PRO_API_KEY': 'my api key'
    },
    json: true,
    gzip: true
  };

const searchCrypto = async () => {
    try {
        const response =  await axios.get('https://pro- 
                          api.coinmarketcap.com/v1/cryptocurrency/quotes/latest', options);
        setResults(response.data);
    } catch (error) {
        console.log(error);        
    }
}

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

return [searchCrypto, results];

} }

You cannot use object in Flatlist you need to create an array from your response u can edit the searchCrypto function like this:您不能在 Flatlist 中使用对象,您需要从您的响应中创建一个数组,您可以像这样编辑searchCrypto函数:

useResults.js使用结果.js

const searchCrypto = async () => {
    try {
        const response =  await axios.get('https://pro- 
                          api.coinmarketcap.com/v1/cryptocurrency/quotes/latest', options);

        const newArr = [];
        Object.keys(response.data.data).map( (key,index)=>{

            newArr.push(response.data.data[key]);
        });

        // console.log(newArr)
         setResults(newArr)

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

At last in renderItem u can use just item instead of result最后在 renderItem 中你可以只使用item而不是 result

import React from 'react';
import { View, Text, FlatList, StyleSheet, TextBase } from 'react-native';
import { createAppContainer } from 'react-navigation';
import useResults from '../hooks/useResults';

const TopCryptoList = ( ) => {

    const [searchCrypto, results] = useResults();

    console.log("THIS WE HAVE: " + results);

    return (
        <View style={styles.container}>
            <FlatList
                showsVerticalScrollIndicator={false}
                data={ results }
                keyExtractor={( item) => item.id}
                renderItem={({ item}) => {
                    return (
                        <Text key={ item.id } style={styles.item}>{item.name}</Text>
                    );
                }}
            />
        </View>
    )  
}

I have tried it works, hope this will help you我已经试过了,希望对你有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM