首页 > 解决方案 > React hook 没有更新从 fetch 函数接收到的数据

问题描述

Text 对象继续显示“Pokemon”而不是pokemon.name. 有任何想法吗?

export default function App() {
  const getRandomPokemon = async () => {
    const randomID = Math.floor(Math.random() * 898);
    const uri = `https://pokeapi.co/api/v2/pokemon/${randomID}`;
  
    return fetch(uri)
    .then(response => response.json())
    .then(data => {
      return {
        name: data.forms[0].name,
        height: data.height,
        weight: data.weight,
      };
    })
  }

  const [FirstCard, setFirstCard] = React.useState("Pokemon");

  return (
    <View style={styles.container}>
      <CardStack 
      loop={true} 
      style={styles.cardStack}
      onSwipeStart={async () => {
        const pokemon = await getRandomPokemon();
        setFirstCard(await pokemon.name)
        console.log(pokemon)
      }}
      >
        <Card style={styles.card}><Text>{FirstCard}</Text></Card>
        <Card style={styles.card}><Text>2</Text></Card>
      </CardStack>
    </View>
  );
}

const styles = StyleSheet.create({
  ...
});

标签: javascriptreact-nativereact-hooksfetch

解决方案


这是您使用的软件包的问题。看

github.com/lhandel/react-native-card-stack-swiper/issues/76


你不需要等待任何东西,只需在 then 函数中获取并设置第一张卡片。

export default function App() {
  const [FirstCard, setFirstCard] = React.useState("Pokemon");
  const getRandomPokemon = () => {
    const randomID = Math.floor(Math.random() * 898);
    const uri = `https://pokeapi.co/api/v2/pokemon/${randomID}`;
    fetch(uri)
    .then(response => response.json())
    .then(data => {
        setFirstCard(data.forms[0].name);
    })
  }
  useEffect(()=>{console.log(FirstName);},[FirstCard]);
  return (
    <View style={styles.container}>
      <CardStack 
      loop={true} 
      style={styles.cardStack}
      onSwipeStart={() => {
         getRandomPokemon();
     }}
      >
        <Card style={styles.card}><Text>{FirstCard}</Text></Card>
        <Card style={styles.card}><Text>2</Text></Card>
      </CardStack>
    </View>
  );
}

推荐阅读