javascript - 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({
...
});
解决方案
这是您使用的软件包的问题。看
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>
);
}
推荐阅读
- php - Paypal Payflow 透明重定向错误代码:PL001
- mongodb - 如何在开玩笑测试中正确关闭猫鼬连接
- testing - 集成测试,通配符忽略标签
- mongodb - 如何以公里为单位计算 LineString 距离?
- laravel-5 - 将 v-html 属性与 vue-i18n 标签中的标记结合起来
- c# - 从 .NET 控制器到 Java REST 服务的 HTTP POST 文件
- python - 如何在不使用 numpy 数组的情况下从 python 字典中访问“行”的元素
- multithreading - 如何在 Java 中进行异步线程执行?
- java - 手动调用 javax.swing.Timer 的 actionPerformed
- python-3.x - 使用 python 3.6 从 genfromtxt numpy date “TypeError: must be str, not bytes” 中从文件与 Internet 导入