如何在函数中添加id搜索产品



我有代码

类别Action.js

import {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产品进行额外搜索,并将其放入对象类别中(例如,具有产品数组的关键产品(,即发出另一个异步请求。但是我不能在async函数中创建async。

const response = await axios.get('/api/category/categories')
const categories = []
categories.push(response.data.data)

也许我提出的问题不对,但我需要下一个逻辑。

  1. 为类别生成axios.get
  2. 获取类别
  3. 通过categoryID生成新的axios.get,并作为放入对象Category中的数组产品进行响应谢谢

如果我是对的,您想在提取类别后,在将类别发送到商店之前,直接提取产品并将其添加到阵列中吗?如果是这样的话,你可以通过类别进行映射:

const categoriesWithProducts = await Promise.all(
categories.map(
async category => {
const products = await 'INSERT AXIOS REQUEST HERE';
return {
...category,
products
}
}
)
)

然后将categoriesWithProducts传递到分派函数中。

最新更新