繁体   English   中英

来自 API 调用的 React-Native 变量引发错误

[英]React-Native variable from API call is throwing an error

我对我的 react-native 真的很生疏,已经有 4 年没碰过它了。

我正在尝试从公开的 API 中提取加密货币价格(如下面的代码所示)。 我想我得到了价格,但将这个价值打包成可用的东西被证明是困难的。 我究竟做错了什么? 要么我没有正确设置 const,要么发生了其他事情。

import React, {Component, useState, useEffect} from 'react';
import {AppRegistry, StyleSheet, Text, View} from 'react-native';

const getPriceFromApi = () => {
  //GET request
  fetch('https://api.coingecko.com/api/v3/simple/price?ids=bone-shibaswap&vs_currencies=usd', {
    method: 'GET',
  })
    .then((response) => response.json())
      //If response is json then in success
    .then((responseJson) => {
      //Success
      return responseJson;
    })
}

const App = () => {
  const [price, setPrice] = useState([]);

  useEffect(() => {
    const fetchPrice = async () => {
      const data = await getPriceFromApi();
      setPrice(data);
      // this should produce ONE value and one value only. 
      // however it’s throwing an error, grrrrr. 
    }
  }, [getPriceFromApi])

  return ();

type Props = {};
export default class MyApp extends Component<Props> {
  render() {
    return (
      <View style={styles.container}>
      <Text style={styles.bone}>
          🍖
        </Text>
        <Text style={styles.welcome}>
          you have > 120.00
        </Text>
        <Text style={styles.instructions}>
          the value of bone is: 
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#2A2734',
  },
  bone: {
    fontSize: 64,
    textAlign: 'center',
    margin: 10,
    color: 'red'
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
    color: 'white'
  },
  instructions: {
    textAlign: 'center',
    color: '#B0B0B0',
    marginBottom: 5,
  },
});

// You must register the main component
// with the same name as the project
AppRegistry.registerComponent(
  'bone-price', () => MyApp
);

如果您正在编写另一个 function 用于从 API 获取数据,您可能会忘记通过 fetch 返回值。 它总是返回未定义的。

您应该修改 function getPriceFromApi()。

const getPriceFromApi = () => {
  //This return is for function - getPriceFromApi()
  return fetch('https://api.coingecko.com/api/v3/simple/price?ids=bone-shibaswap&vs_currencies=usd', {
    method: 'GET',
  })
    .then((response) => response.json())
    .then((responseJson) => {
      //This return is for function - fetch()
      return responseJson;
    })
}

暂无
暂无

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

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