REDUX - 当我执行调度循环时如何存储 ARRAY id?

REDUX - how to store ARRAY id's when i do a dispatch loop?

我需要保存在商店中循环获取时收到的 ID,但我没有意识到如何迭代对象

这是我的动作


export function uploadImage(files) {
    return function async(dispatch) {
        const myHeaders = new Headers();
        myHeaders.append("Authorization", `Token ${localStorage.getItem('***')}`)
        for(let i = 0; i < files.length;  i++) {
            const formdata = new FormData();
            formdata?.append("image", files[i], files[i].name);
            
            fetch(`${process.env.REACT_APP_URL_API}/api/images/`, {
                'method': "POST",
                'headers': myHeaders,
                'body': formdata,
                'redirect': 'follow'
            })
                .then(resp => resp.json())
                .then(json => dispatch(activeImage(json.id)))
        }
    }
}

export const activeImage = ( id ) => ({
    type: "PUSH_ID_IMAGE",
    payload: id
});


我的减速器:


case "PUSH_ID_IMAGE":
            return{
                ...state,
                images: [...action.payload]
            }
        

Redux 操作默认不支持异步操作,您可以尝试使用 redux-thunk

它允许您 return 一个函数作为一个动作,并允许您访问 dispatchgetState 这样您就可以从函数内部将事件分派给您的 reducer 以及能够检索状态

安装后 redux-thunk 你可以写这样的东西作为你的动作:

const uploadImage = files => {
  return async (dispatch, getState) => {
    // ... your proccessing / loop here
    
    // ... inside the loop
    const response = await fetch(`${process.env.REACT_APP_URL_API}/api/images/`, {
        'method': "POST",
        'headers': myHeaders,
        'body': formdata,
        'redirect': 'follow'
    })
      .then(resp => resp.json())
     
    dispatch({
      type: "PUSH_ID_IMAGE",
      payload: response 
    })  // send the data returned from "resp.json"
  }
}