簡體   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