簡體   English   中英

React Native:一旦異步 function 返回變量,如何在 Text 元素中顯示變量?

[英]React Native: How do I display a variable in a Text element once an async function has returned it?

fetch function 返回所有正確信息; 我知道這一點,因為它都被記錄到控制台,但是一旦 json 數據保存到口袋妖怪 class 中, Text元素就不會顯示口袋妖怪名稱。 我使用 expo 順便說一句。

export default function App() {
  let Pokemon = {
    getInfo: async (name) => {
      name = name.toLowerCase();

      const uri = `https://pokeapi.co/api/v2/pokemon/${name}`;
      
      await fetch(uri)
      .then(response => response.json())
      .then(data => {
        Pokemon.name = data.forms[0].name;
        Pokemon.img = data.sprites.front_default;
      })
      .catch(error => {
        if(error){
          console.log(`Failed to find "${name}"`)
        }
      });

      console.log(await Pokemon.name, await Pokemon.img)
    }
  }

  const [value, onChangeText] = React.useState('Enter A Pokemon');

  return (
    <View style={styles.container}>

      <Text style={styles.title}>{Pokemon.name}</Text>

      <TextInput
      style={styles.textBox}
      clearTextOnFocus={true}
      onChangeText={async text => {
        onChangeText(text)
        Pokemon.getInfo(text)
      }}
      value={value}
      />

      <StatusBar style="auto" />
    </View>
  );
}

叫我cap'n hook:

export default function App() {
  let Pokemon = {
    getInfo: async (name) => {
      name = name.toLowerCase();

      const uri = `https://pokeapi.co/api/v2/pokemon/${name}`;
      
      await fetch(uri)
      .then(response => response.json())
      .then(data => {
        Pokemon.name = data.forms[0].name;
        Pokemon.img = data.sprites.front_default;
      })
      .catch(error => {
        if(error){
          console.log(`Failed to find "${name}"`)
        }
      });

      console.log(await Pokemon.name, await Pokemon.img)
    }
  }

  

  const [value, onChangeText] = React.useState('Enter A Pokemon');
  const [myText, setMyText] = React.useState("My Original Text");

  return (
    <View style={styles.container}>

      <Text style={styles.title}>{myText}</Text>

      <TextInput
      style={styles.textBox}
      clearTextOnFocus={true}
      onChangeText={async text => {
        onChangeText(text)
        await Pokemon.getInfo(text)
        setMyText(await Pokemon.name)
      }}
      value={value}
      />

      <StatusBar style="auto" />
    </View>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM