我有三片ProductSlice
,CategorySlice
和BrandSlice
片.每个切片有createAsyncThunk
个,对产品、类别和品牌进行提取请求.
CategorySlice
(BrandSlice
个相同):
export const fetchCategories = createAsyncThunk('category/fetchCategories', async () => {
const response = await fetch(`${BASE_URL}/categories.json`);
const data = await response.json();
const categories: Category[] = handleObj(data);
return categories;
});
builder.addCase(fetchCategories.fulfilled, (state, { payload }) => {
state.categories = payload;
state.isLoading = false;
});
应用程序组件分派三个FETCH请求.
useEffect(() => {
dispatch(fetchCategories());
dispatch(fetchProducts());
dispatch(fetchBrands());
}, [dispatch]);
我需要从品牌和类别中获得数据.然后获取产品的数据,并向每个产品添加一些数据,然后才将其设置为ProducSlice
状态.数据应该来自品类和品牌.我试着在ProductSlice
-createAsyncThunk
中这样做:
export const fetchProducts = createAsyncThunk<Product[], void, { state: RootState }>(
'product/fetchProducts',
async (_, { getState }) => {
const response = await fetch(`${BASE_URL}/products.json`);
const data = await response.json();
const products: Product[] = handleObj(data);
const { brands } = await getState().brand;
const { categories } = await getState().category;
const productsWithUpdatedBrandsAndCategories = products.map((product) => {
const category = categories.find((category) => category.id === product.category.id);
const brand = brands.find((brand) => brand.id === product.brand.id);
if (!category && !brand) return product;
return {
...product,
category: {
...category,
name: category && category.name,
},
brand: {
...brand,
name: brand && brand.name,
},
};
}) as Product[];
return productsWithUpdatedBrandsAndCategories;
}
);
问题是,有时,thunk中ProductSlice中的品牌或类别是空数组(我的意思是,当数据不是来自其他切片时,thunk就会触发……所以productsWithUpdatedBrandsAndCategories
什么都不做).那该怎么处理呢?