我在我的 React 项目中使用 nextui。在我项目的一个部分中,我通过 fetch 从服务器获取产品,并使用 ProductCard 组件在 dom 中显示产品信息(每个产品卡都是 app.jsx 中的一个组件),并希望在获取产品和 dom 中的 ahow 之前使用 nextui 骨架组件。现在,我是在获取之前在 ProductCard 组件中还是在 app.jsx 中使用骨架?
例如:
App.jsx:
{products.length?
<Skeleton>
//codes
</Skeleton>
:
products.map(product=><ProductCard {...product}/>)
}
是否真实、干净?
我没有尝试,因为我不确定这是真的吗? 但我知道它有效。
通常,在获取调用返回结果之前,您希望某些卡处于骨架加载器模式。
在您的情况下,您的骨架将仅绘制一个骨架组件,具体取决于其内部的内容,因为该代码并未真正显示在您的示例中。
我会说做这样的事情:
export const MyComponent = () => {
const [products, setProducts] = React.useState([]);
const SKELETONS_TO_SHOW = 3
// fetch logic here
if (products.length === 0) {
return Array.from({ length: SKELETONS_TO_SHOW }).map((_, index) =>
<Skeleton key={index} />
);
}
return products.map((product) => <Product product={product}>);
};