【问题标题】:React hook isn't updating data received from a fetch functionReact hook 没有更新从 fetch 函数接收到的数据
【发布时间】:2020-12-12 19:46:28
【问题描述】:

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({
  ...
});

【问题讨论】:

  • 你为什么使用await pokemon.name?不应该只是pokemon.name吗?
  • 虽然一些语法元素不是必需的(如下面的回答所示),但这段代码基本上应该可以工作。请参阅codesandbox.io/s/sharp-vaughan-pn1uj?file=/src/App.js - 效果很好。

标签: javascript react-native react-hooks fetch


【解决方案1】:

可能pokemon.name 不是Promise。在这种情况下,您应该删除 pokemon.name 之前的 await。

【讨论】:

  • 没用。顺便说一句,所有正确的口袋妖怪信息都会被记录下来。
【解决方案2】:

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

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

【讨论】:

  • 是的,还是不行,是不是和我用的卡组件有关?它来自外部节点包。
  • 在您的代码中添加 useEffect 以查看名称是否已更新。查看更新的代码。
  • 是的,当我用/console.log(FirstCard) 运行代码时,它会打印出一个口袋妖怪名称,但卡片仍然只显示“口袋妖怪”
  • 这意味着您的 Card 组件有问题,您使用的是哪个包?
  • react-native-card-stack-swiper
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 2021-03-03
相关资源
最近更新 更多