正如您在图像上看到的那样,获取数据并将其显示在屏幕上后,橙色按钮(在中心)出现1秒,然后消失.
组件代码:
const Home: FC = () => {
const { pizzas, loading, error, count } = useAppSelector(
(state) => state.pizzas
)
const { categoryID, searchValue, currentPage, sortNameObj } =
useAppSelector((state) => state.filter)
const dispatch = useAppDispatch()
const handleChangeCategory = useCallback((index: number) => {
dispatch(setCategoryID(index))
dispatch(setCurrentPage(1))
}, [])
const handleChangePage = (page: number) => {
dispatch(setCurrentPage(page))
}
const pizzaList = pizzas?.map((item) => {
const pizzaImg = pizzaImagesMiddle[item.title]
return <PizzaCard key={item.id} item={item} pizzaImg={pizzaImg} />
})
const skeletons = [...new Array(4)].map((_, index) => (
<PizzaSkeleton key={index} />
))
const loadedPizzas = loading ? skeletons : pizzaList
useEffect(() => {
dispatch(fetchPizzas())
}, [categoryID, searchValue, sortNameObj, currentPage])
if (error) {
return <EmptyResult title='Произошла ошибка' />
}
if (!loading && (!pizzas || pizzas?.length === 0)) {
return <EmptyResult title='Пиццы не найдены' />
}
return (
<div className={styles.home__container}>
<div className={styles.content__header}>
<Categories
handleChangeCategory={handleChangeCategory}
value={categoryID}
/>
<Sort sortNameObj={sortNameObj} />
</div>
<h2>Все пиццы</h2>
<section className={styles.content__list}>{loadedPizzas}</section>
<Pagination
handleChangePage={handleChangePage}
currentPage={currentPage}
itemsLength={count}
/>
</div>
)
}
这是因为在条件if (!loading && (!pizzas || pizzas?.length === 0))
时判断披萨长度.不判断空长if (!loading && !pizzas)
,一切顺利.但我需要判断数组是否为空.
默认情况下,披萨长度为空(因此在获取数据之前我有空数组)
披萨片:
const initialState: PizzasState = {
pizzas: [],
loading: false,
error: null,
count: 0
}
const pizzasSlice = createSlice({
name: 'pizzas',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(fetchPizzas.pending, (state) => {
state.loading = true;
state.pizzas = [];
state.error = null;
state.count = 0
});
builder.addCase(fetchPizzas.fulfilled, (state, action) => {
state.pizzas = action.payload.items;
state.error = null;
state.count = action.payload.count;
state.loading = false
});
builder.addCase(fetchPizzas.rejected, (state, action) => {
state.pizzas = [];
state.count = 0;
if (action.payload) {
state.error = action.payload.message
} else {
state.error = action.error.message
};
state.loading = false
})
}
})
问:如何正确避免闪烁<EmptyResult/>
1秒?