【发布时间】:2021-10-31 23:54:26
【问题描述】:
我已经在函数 fetchProduct() 中设置了一个产品详细信息来设置产品使用状态。
const [ product, setProduct ] = useState({})
const fetchProduct = () => {
const apiURL = //api url;
fetch(apiURL)
.then((response) => response.json())
.then(res => {
setProduct(res.data[0])
})
.catch(error => {
console.error(error);
});
}
在我在 useEffect 挂钩中调用此函数之后。我已经通过 colsole 日志检查了产品是否已设置或未调用
useEffect(() => {
fetchProduct()
console.log(product)
return () => {
}
},[])
我在控制台中得到以下结果
{}
然后我再次刷新结果显示在控制台中。为什么第一次结果是空对象。感谢帮助
【问题讨论】:
-
它最初是一个空对象,因为这是
useState({})中的默认值。 -
嘿,谢谢您的回复,我如何才能像最初那样在 useState() 中实现 api fetch 功能
标签: javascript react-native react-native-android use-effect