如何在获取信息React js之前使用map函数



我用这种结构做主页

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

[Edit]:要在等待数据时显示不同的内容,可以这样做:

if (!responseProducts) return <Loader />;
else
return (
<IonPage>
...
</IonPage>
);

但在这里,您需要触发组件的渲染。要么将产品置于一个状态并使用setState,要么在父级中处理获取并将产品作为propr传递(仍然需要一个状态(。


您需要responseProducts的默认值。你可以使用useEffect钩子和useState钩子来实现这一点:

const Login: React.FC = () => {
const [products, setProducts] = useState({});
const [didMount, setDidMount] = useState(false);
useEffect(() => {
if(!didMount){
// I don't know where this comes from so i'll use it like this, adapt if needed
useIonViewDidEnter(async () => {
await fetchProducts();
});
} else {
!didMount && setDidMount(true);
}
});
/* this is the initialization of my variable with products*/
let responseProducts: getProductsReponse;
/* function to fetch the api*/

const fetchProducts = async () => {
await ProductService.getProducts().then((products) => {
// responseProducts = products.data;
const data: getProductsReponse = products.data;
setProducts(data);
});
};
// You could even put a different return (a loader for exemple) while your data arent available
return (
<IonPage>
<IonContent>
<IonSlides pager={false} options={slideOpts}>
{/* this is now strange, you can adapt what you put in your state */}
{products.content.products.map((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>
);
};

最新更新