[英]How to get data from fetch inside a function in React Native
I am trying to fetch data from external api and show that on display.我正在尝试从外部 api 获取数据并在显示屏上显示。 When I press button it calls function which console things normally but can't show returned value.当我按下按钮时,它会调用正常控制台但无法显示返回值的函数。
export default function HomeScreen() {
return (
<View style={styles.container}>
<Button title='show data' onPress={loadText}/>
<Text>{loadText}</Text>
</View>
);
function loadText(){
fetch('http://192.168.88.253:5000/read')
.then((response) => response.json())
.then((responseJson) => {
return (
console.log(responseJson.city)
);
})
.catch((error) => {
console.error(error);
});
}
}
If I understand it, loadText
function must return responseJson.city
value as a string.如果我理解它, loadText
函数必须以字符串形式返回responseJson.city
值。 How can I show it in <View>
or <Text>
?如何在<View>
或<Text>
显示它?
export default function HomeScreen() {
constructor(props){
super(props);
this.state = {
city: ''
}
}
return (
<View style={styles.container}>
<Button title='show data' onPress={() => this.loadText()}/>
<Text>{this.state.city}</Text>
</View>
);
loadText(){
fetch('http://192.168.88.253:5000/read')
.then((response) => response.json())
.then((responseJson) => {
this.setState({city: responseJson.city});
})
.catch((error) => {
console.error(error);
});
}
}
you can use alert()
to display the data.您可以使用alert()
来显示数据。
alert is the popup which will be displayed on the mobile screen.警报是将显示在移动屏幕上的弹出窗口。
export default function HomeScreen() {
return (
<View style={styles.container}>
<Button title='show data' onPress={loadText}/>
<Text>{loadText}</Text>
</View>
);
function loadText(){
fetch('http://192.168.88.253:5000/read')
.then((response) => response.json())
.then((responseJson) => {
return (
alert(JSON.stringfy(responseJson.city))
);
})
.catch((error) => {
alert(JSON.stringfy(error));
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.