[英]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.