Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/471.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用上下文API时访问全局状态_Javascript_Reactjs_React Native - Fatal编程技术网

Javascript 使用上下文API时访问全局状态

Javascript 使用上下文API时访问全局状态,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我使用了用于状态管理的上下文API,它成功地访问了组件中的数据。使用的数据是外汇对的货币价格。当从API获取数据时,该数据在1000毫秒的间隔后不断更新。如何以与在第一个组件中接收数据相同的方式在另一个组件中访问该数据。在navigation.navigate('CreateAlertScreen)中将价格数据作为参数传递不会传递不断更新的数据。下面是代码 //主屏幕 import React, {useContext} from 'react' import { Text, View, Act

我使用了用于状态管理的上下文API,它成功地访问了组件中的数据。使用的数据是外汇对的货币价格。当从API获取数据时,该数据在1000毫秒的间隔后不断更新。如何以与在第一个组件中接收数据相同的方式在另一个组件中访问该数据。在
navigation.navigate('CreateAlertScreen)
中将价格数据作为参数传递不会传递不断更新的数据。下面是代码

//主屏幕

import React, {useContext} from 'react'
import { Text, View, ActivityIndicator, ScrollView, TouchableOpacity } from 'react-native'
import {ListItem, Card, Button, Icon} from 'react-native-elements'
//import CurrencyPair from '../../CurrencyPair'
import {firebase} from '../../../firebase/config'
import {CurrencyContext} from '../../../context/Context'

function HomeScreen({navigation}) {

    const currency = useContext(CurrencyContext);


return (
        <ScrollView>
    
        <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}
        //passing data from HomeScreen to CreateAlert Screen with  the initialized parameters
        onPress = {() => navigation.navigate('CreateAlertScreen')}
        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
import React,{useContext}来自“React”
从“react native”导入{Text,View,ActivityIndicator,ScrollView,TouchableOpacity}
从“react native elements”导入{ListItem、卡片、按钮、图标}
//从“../../CurrencyPair”导入CurrencyPair
从“../../../firebase/config”导入{firebase}
从“../../../context/context”导入{CurrencyContext}
功能主屏幕({navigation}){
const currency=useContext(CurrencyContext);
返回(
欢迎
firebase.auth().signOut()}/>
导航。导航(“AlertScreen”)}/>
{currency.data.prices&¤cy.data.prices.map((价格,指数)=>{
返回(
导航。导航('CreateAlertScreen')}
底部分隔器>
{currency.data.prices[index].instrument}{currency.data.prices[index].closeoutAsk}{currency.data.prices[index].closeoutBid}
)
})
}
)
}
导出默认主屏幕
//上下文

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}
import React,{createContext,useState,useffect}来自“React”
从“react native”导入{ActivityIndicator}
从“../utils/axios”导入axios
const CurrencyContext=createContext();
const CurrencyProvider=(道具)=>{
const[data,setData]=useState([])
常量[isLoading,setIsloading]=useState(真)
useffect(()=>{
常量间隔=设置间隔(()=>{
const fetchpairs=async()=>{
const results=等待axios.get(3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/3/美元(加元%2美元(日元%2美元(瑞士法郎%2美元(南非兰特%2美元(墨西哥元))
setData(results.data)
setIsloading(错误)
}
fetchpairs()
},1000)
}, []);
如果(孤岛加载){
返回(
)
}否则
返回(
{props.children}
)
}
导出{CurrencyProvider,CurrencyContext}
//CreateAlertScreen

import React, {useContext,useState} from 'react'
import { View, Text,TextInput, StyleSheet, Picker, TouchableOpacity, Button, PushNotificationIOS } from 'react-native'
import {Card, CheckBox } from 'react-native-elements'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import {FoodContext} from '../../../context/Context'
import styles from './styles'

const CreateAlertScreen =()=> {

    const create = useContext(FoodContext);
// hook for the message textinput
    const [message, setMessage] = useState(null)

    return (
        <View style={styles.container}>
            
             <KeyboardAwareScrollView
                style={{ flex: 1, width: '100%' }}
                keyboardShouldPersistTaps="always">
            <Card>
                <Card.Title>
                    Pair:   {} 
                </Card.Title>
                <Card.Divider/>
                <Text style={{textAlign:"center"}}>
               BidPrice: {BidPrice} / AskPrice:{AskPrice}
                </Text>
                <Card.Divider/>
                <Text style={{textAlign: "center"}}>
                    Alert When : 
                </Text>

                <TextInput
          style={styles.textInputStyle}
          placeholder="Price"
          placeholderTextColor="#60605e"
          numeric
          keyboardType='decimal-pad'    
        />
                <Card.Divider/> 

                <TextInput
                value={message}
                onChangeText={(message) =>setMessage(message)}
                style={styles.input}
                />
                <TouchableOpacity
                style={styles.button}
                onPress={() => navigation.navigate('AlertScreen', {
                    alert: message
                })}
                >
                    <Text style={styles.buttonTitle}>CreateAlert</Text>
                </TouchableOpacity>
                

            
        </Card>
        </KeyboardAwareScrollView>
        </View>
    )
}

export default CreateAlertScreen
import React,{useContext,useState}来自“React”
从“react native”导入{View、Text、TextInput、样式表、选择器、TouchableOpacity、Button、PushNotificationIOS}
从“反应本机元素”导入{Card,CheckBox}
从“react native KeyboardAwareScrollView”导入{KeyboardAwareScrollView};
从“../../../context/context”导入{FoodContext}
从“./styles”导入样式
const CreateAlertScreen=()=>{
const create=useContext(FoodContext);
//消息textinput的钩子
const[message,setMessage]=useState(null)
返回(
对:{}
投标价格:{BidPrice}/AskPrice:{AskPrice}
在以下情况下发出警报:
设置消息(消息)}
style={style.input}
/>
导航。导航('AlertScreen'{
警报:消息
})}
>
CreateAlert
)
}
导出默认CreateAlertScreen

据我所知,您的应用程序设置错误。 在顶级组件上创建上下文,并在上下文提供程序中包装整个应用程序渲染。 然后,每个组件都可以访问您的上下文

直接从文档中

const themes = {
  light: {
    foreground: "#000000",
    background: "#eeeeee"
  },
  dark: {
    foreground: "#ffffff",
    background: "#222222"
  }
};

const ThemeContext = React.createContext(themes.light);

function App() {
  return (
    <ThemeContext.Provider value={themes.dark}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return (
    <button style={{ background: theme.background, color: theme.foreground }}>
      I am styled by theme context!
    </button>
  );
}
const主题={
灯光:{
前景:“000000”,
背景:“eeeeee”
},
黑暗:{
前景:“ffffff”,
背景:“22222”
}
};
const ThemeContext=React.createContext(themes.light);
函数App(){
返回(
);
}
功能工具栏(道具){
返回(
);
}
函数按钮(){
const theme=useContext(ThemeContext);
返回(
我的风格由主题上下文!
);
}
如您所见,整个应用程序包装在ThemeSecontext.Provider中,将themes.light对象作为值传递给提供者。 然后使用useContext钩子向下访问2个“级别”