简体   繁体   English

使用来自 API 的数据在 React Native 中进行条件渲染

[英]Using data from an API for conditional rendering in react native

I'm buiding an application that receives foreign exchange currency pairs eg EURUSD with their respective prices eg EURUSD AskPrice: 0.90345 BidPrice: 0.90365 .我正在构建一个接收外汇货币对的应用程序,例如 EURUSD 及其各自的价格,例如 EURUSD AskPrice: 0.90345 BidPrice: 0.90365 。 The user of the application is supposed to set the price in a textInput at which they would like to be alerted once that price is reached.应用程序的用户应该在 textInput 中设置价格,一旦达到该价格,他们希望在该处收到警报。 I have tried creating a function for this but it logs the input price immediately instead of checking the condition first and then waiting for the condition to be met first before logging.我曾尝试为此创建一个函数,但它会立即记录输入价格,而不是先检查条件,然后在记录之前先等待条件满足。 Below is the Code:下面是代码:

//Datafetching
import React, {createContext, useState, useEffect}from 'react'
import {ActivityIndicator} from 'react-native'
import axios from '../utils/axios'

const CurrencyContext = createContext();

const CurrencyProvider =(props) => {
    const [data, setData] = useState([])
    const [isLoading, setIsloading] = useState(true)

    useEffect(() => {
        const interval = setInterval(() => {
            const fetchpairs = async() => {
                const results = await axios.get('/v3/accounts/101-004-14328428-002/pricing?instruments=AUD_CAD%2CAUD_CHF%2CAUD_JPY%2CAUD_NZD%2CAUD_USD%2CCAD_CHF%2CCAD_JPY%2CCHF_JPY%2CEUR_AUD%2CEUR_CAD%2CEUR_CHF%2CEUR_GBP%2CEUR_NOK%2CEUR_NZD%2CEUR_USD%2CGBP_AUD%2CGBP_CAD%2CGBP_CHF%2CGBP_USD%2CGBP_JPY%2CNZD_CAD%2CNZD_CHF%2CNZD_JPY%2CUSD_CAD%2CUSD_JPY%2CUSD_CHF%2CUSD_ZAR%2CUSD_MXN')
                setData(results.data)
                setIsloading(false)
            }
            fetchpairs() 
        },1000)
      }, []);

      if(isLoading) {
        return (
            <ActivityIndicator size="large"/>
        )
    }else
    return (
        <CurrencyContext.Provider
        value={{
            data,
            setData,
            isLoading,
            setIsloading
        }}>
            {props.children}

        </CurrencyContext.Provider>

       
    )
}

export {CurrencyProvider, CurrencyContext}

//HomeScreen //主屏幕

import React, {useContext, useState, useEffect} from 'react'
import { Text, View, ScrollView, TouchableOpacity, Modal, TextInput, ToastAndroid, Picker, Alert } from 'react-native'
import {ListItem, Card, Button, Icon} from 'react-native-elements'
import {ActionSheet} from 'native-base'
//import CurrencyPair from '../../CurrencyPair'
import {firebase} from '../../../firebase/config'
import {CurrencyContext} from '../../../context/Context'
import styles from '../HomeScreen/styles'



function HomeScreen({navigation, props}) {

    const currency = useContext(CurrencyContext);
    //hook for the modal
    const [modalopen, setModalOpen] = useState(false)
//hook for the clicked currency pair
    const [clickedindex, setClickedIndex]  = useState(0)
//hook for the actionsheet
   const[sheet, setSheet] = useState(null)
   //Hooks for the alert
   const [pricealert, setPricealert] = useState('')



//function for checking alert condition

  const checkAlertCondition = (pricealert) => {
    if(pricealert >= {...currency.data.prices[clickedindex].closeoutAsk} ){
      setPricealert(pricealert)
      console.log("Price" + pricealert + "has been hit")
    }
    else if(pricealert <=  {...currency.data.prices[clickedindex].closeoutAsk})
    {
      setPricealert(pricealert)
      console.log("Price" + pricealert + "has been hit")

    }
    else
    {
      console.log("Set your alert price")
  
    }
  }
        //toast method that will be called when the ok button is called
    const showToastWithGravityAndOffset = () => {
      ToastAndroid.showWithGravityAndOffset(
        "Alert created successfully",
        ToastAndroid.SHORT,
        ToastAndroid.BOTTOM,
        25,
        50
      );
    };
    const BUTTONS = [
      { text: "SMS", icon: "chatboxes", iconColor: "#2c8ef4" },
      { text: "Email", icon: "analytics", iconColor: "#f42ced" },
      { text: "Push Notification", icon: "aperture", iconColor: "#ea943b" },
      { text: "Delete", icon: "trash", iconColor: "#fa213b" },
      { text: "Cancel", icon: "close", iconColor: "#25de5b" }
    ];
    const DESTRUCTIVE_INDEX = DESTRUCTIVE_INDEX;
    const CANCEL_INDEX = CANCEL_INDEX;
return (
        <ScrollView>
          <Modal
          visible={modalopen}
          animationType={"fade"}
          >
            <View style={styles.modal}>
              <View>
                <Text style={{textAlign: "center", fontWeight: "bold"}}>
               {currency.data.prices[clickedindex].instrument}
              </Text>
              <Text style={{textAlign: "center"}}>
              {currency.data.prices[clickedindex].closeoutAsk}/{currency.data.prices[clickedindex].closeoutBid}
              </Text>
              <Card.Divider/>

              <View style={{ flexDirection: "row"}}>
                <View style={styles.inputWrap}>
                
                    <TextInput
          style={styles.textInputStyle}
          value={pricealert}
          onChangeText = {(pricealert) => setPricealert(pricealert)}
          placeholder="Alert Price"
          placeholderTextColor="#60605e"
          numeric
          keyboardType='decimal-pad'    
        />
                </View>
                <View style={styles.inputWrap}> 
                </View>

              </View>   
          <TouchableOpacity 
          onPress={() =>
            ActionSheet.show(
              {
                options: BUTTONS,
                cancelButtonIndex: CANCEL_INDEX,
                destructiveButtonIndex: DESTRUCTIVE_INDEX,
                title: "How do you want to receive your notification"
              },
              buttonIndex => {
                setSheet({ clicked: BUTTONS[buttonIndex] });
              }
            )}
            style={styles.button}
          >
            <Text>ActionSheet</Text>
          </TouchableOpacity>

              <TouchableOpacity style={styles.button}
               onPress={() => {setModalOpen(false); checkAlertCondition(pricealert);showToastWithGravityAndOffset();} }>
                <Text style={styles.buttonTitle}>OK</Text>
              </TouchableOpacity>
              </View>
            </View>
          </Modal>
        <Card>
            <Text style={{textAlign: "center"}}>
                Welcome
            </Text>
            <Button title="Sign Out" type="outline" onPress ={() => firebase.auth().signOut()}/>
            <Button title="My Alerts"  onPress ={() =>navigation.navigate("AlertScreen") }/>
            
        </Card>

        <View>
            {currency.data.prices && currency.data.prices.map((prices, index) => {
                return (
      <ListItem
        key={index}
        onPress = {() => {setModalOpen(true);setClickedIndex(index);}} 
        bottomDivider>
        <ListItem.Content>
            <ListItem.Title>
            {currency.data.prices[index].instrument}        {currency.data.prices[index].closeoutAsk}         {currency.data.prices[index].closeoutBid}
            </ListItem.Title>
        </ListItem.Content>
      </ListItem>     
                )
            })
}
        </View>
    </ScrollView>
)
}
export default HomeScreen

在此处输入图片说明

inside onPress you are calling checkAlertCondition but with no params yet inside that function you are expecting the pricealert also you are trying to use >= with the left hand side being an object.在 onPress 内部,您正在调用checkAlertCondition但在该函数中还没有参数,您正在期待pricealert并且您正在尝试使用 >= 并且左侧是一个对象。

Try this:尝试这个:

const checkAlertCondition = (pricealert) => {
  if(currency.data.prices[clickedindex].AskPrice >= pricealert){
    setPricealert(pricealert)
    console.log("Price" + pricealert + "has been hit")
  }
}

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

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