[英]Accessing global state when using Context API
我已经使用上下文 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, {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, {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
据我所知,您的应用程序设置错误。 在顶级组件上创建上下文并将整个应用程序渲染包装在上下文提供程序中。 然后每个组件都可以访问您的上下文。 (前提是你使用 useContext)
直接从文档
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>
);
}
如您所见,整个应用程序都包含在 ThemeContext.Provider 中,并将 themes.light 对象作为值传递给 Provider。 然后使用 useContext 钩子向下访问 2 个“级别”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.