【发布时间】:2020-08-17 11:40:26
【问题描述】:
我正在用这种结构做一个主页
const Login: React.FC = () => {
[ ... ]
return (
<IonPage>
<IonContent>
<IonSlides pager={false} options={slideOpts}>
{
responseProducts.content.products.map(function(item,i) {
return <IonSlide key={i} >
<IonCard onClick={Product}>
<IonImg src={item.urlImg}></IonImg>
<IonCardHeader>
<IonCardSubtitle>{item.ref}</IonCardSubtitle>
<IonCardTitle>{item.title}</IonCardTitle>
</IonCardHeader>
</IonCard>
</IonSlide>
})
}
</IonSlides>
</IonContent>
</IonPage>
);
};
当我获取服务器 api 时,变量 responseProducts.content.products 是一个产品数组。
我试图在应用程序启动之前获取 api 来初始化变量:
const Login: React.FC = () => {
/* this is the initialization of my variable with products*/
let responseProducts : getProductsReponse;
/* function to fetch the api*/
useIonViewDidEnter(async () => {
await fetchProducts();
});
const fetchProducts = async() =>{
await ProductService.getProducts()
.then((products ) =>{
responseProducts = products.data;
})
}
return (
<IonPage>
<IonContent>
<IonSlides pager={false} options={slideOpts}>
{
responseProducts.content.products.map(function(item,i) {
return <IonSlide key={i} >
<IonCard onClick={Product}>
<IonImg src={item.urlImg}></IonImg>
<IonCardHeader>
<IonCardSubtitle>{item.ref}</IonCardSubtitle>
<IonCardTitle>{item.title}</IonCardTitle>
</IonCardHeader>
</IonCard>
</IonSlide>
})
}
</IonSlides>
</IonContent>
</IonPage>
);
};
但是我的产品出现了这个错误:
Variable 'responseProducts' is used before being assigned
【问题讨论】:
标签: reactjs react-hooks ionic4 react-functional-component