【发布时间】: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