繁体   English   中英

如何从 React Native 中的函数中的 fetch 获取数据

[英]How to get data from fetch inside a function in React Native

我正在尝试从外部 api 获取数据并在显示屏上显示。 当我按下按钮时,它会调用正常控制台但无法显示返回值的函数。

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);
      });
  }
}

如果我理解它, loadText函数必须以字符串形式返回responseJson.city值。 如何在<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);
      });
  }
}

您可以使用alert()来显示数据。

警报是将显示在移动屏幕上的弹出窗口。

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.

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