我有代码类别Action.jsimport {FETCH_CATEGORIES_START, FETCH_CATEGORIES_SUCCESS, FETCH_CATEGORIES_ERROR} from "./actions-types/categories-actions"import axios from "axios"export function fetchCategories() { return async dispatch => { dispatch(fetchCategoriesStart()) try { const response = await axios.get('/api/category/categories') const categories = [] categories.push(response.data.data) dispatch(fetchCategoriesSuccess(categories)) } catch (e) { dispatch(fetchCategoriesError(e)) } }}export function fetchCategoriesStart() { return{ type: FETCH_CATEGORIES_START }}export function fetchCategoriesSuccess(categories) { return{ type: FETCH_CATEGORIES_SUCCESS, categories }}export function fetchCategoriesError(error) { return{ type: FETCH_CATEGORIES_ERROR , error }}及减速机代码import {FETCH_CATEGORIES_START, FETCH_CATEGORIES_SUCCESS, FETCH_CATEGORIES_ERROR} from "../actions/actions-types/categories-actions"const initialState = { categories: [], loading: false, error: null}export default function categoriesReducer(state = initialState, action){ switch (action.type) { case FETCH_CATEGORIES_START: return { ...state, loading: true } case FETCH_CATEGORIES_SUCCESS: return { ...state, loading: false, categories: action.categories[0] } case FETCH_CATEGORIES_ERROR: return { ...state, loading: false, error: action.error } default: return state }}但是当我获得类别时,我需要按类别 ID 产品进行额外搜索并放入对象类别(例如带有产品数组的关键产品),即发出另一个异步请求。但我无法在异步函数中进行异步。const response = await axios.get('/api/category/categories')const categories = []categories.push(response.data.data)也许我提出的问题不对,但我需要下一个逻辑。为类别制作 axios.get获取类别当数组产品放入对象类别中时,通过类别 ID 和响应创建新的 axios.get 谢谢
1 回答
largeQ
TA贡献2039条经验 获得超7个赞
如果我是对的,您想在获取类别后、将类别分派到商店之前直接获取产品并将它们添加到数组中吗?如果是这样,您可以直接映射类别:
const categoriesWithProducts = await Promise.all(
categories.map(
async category => {
const products = await 'INSERT AXIOS REQUEST HERE';
return {
...category,
products
}
}
)
)
然后将categoriesWithProducts传递到dispatch函数中。
添加回答
举报
0/150
提交
取消