【问题标题】:dispatching Asynchronous action from an array react redux thunk从数组中调度异步操作反应 redux thunk
【发布时间】:2021-01-22 16:42:22
【问题描述】:

根据要求,我们需要从数组列表中进行API调用。已使用redux-thunk进行异步操作。在api调用完成后将请求参数传递给reducer时出现问题。

    # From the container
    let document = [ bankstatement1,bankstatement2];
    document.map(element => {
     dispatch ( actions.uploadFiles(element) )
    });
    # inside actions
    export const uploadFiles = (payload) => {
      return async dispatch => {
        
        const response = await callAPIMiddleware(dispatch, {
          types: ['DOC_UPLOAD_START','DOC_UPLOAD_SUCCESS','DOC_UPLOAD_ERROR'],
          endPoint: ApiEndpoints.DOCUMENT_UPLOAD,
          type: HTTP_METHOD_TYPE.POST,
          payload: payload,
          headers: Headers.multipart,
          
        });
        return response;
      };
    };
    # inside axios middle ware
    export const callAPIMiddleware = async (dispatch, RequestParams) => {
     # calling upload_start ,here also the request payload being asked.     
        dispatch({
            type: "DOC_UPLOAD_START,
            data:RequestParams //bankstatement1,bankstatement2
          });
    
    # let res = await axios.post(endPoint,RequestParams, {
            headers: reqHeaders,
            config: reqConfig,
            });
    if (res && res.data) {
         
            dispatch({
              type:'DOC_UPLOAD_SUCCESS',
              data: res.data,
              param:RequestParams //bankstatement2,bankstatement2 here it is always referring to "bankstatement2" 
            });
    
    }
After the API call is finished, reference to first request parameter is overridden by second one.Can anyone suggest how we can still refer to the first element .

【问题讨论】:

    标签: javascript reactjs redux async-await redux-thunk


    【解决方案1】:

    编辑: 如果您尝试将最后一段逻辑放在“then”中,那么它的范围肯定在那里?

    axios.post(endPoint,RequestParams, {
      headers: reqHeaders,
      config: reqConfig,
      }).then(res => {
        console.log('calling dispatch for ', RequestParams);
        if (res && res.data) {
          dispatch({
            type:'DOC_UPLOAD_SUCCESS',
            data: res.data,
            param: RequestParams,
          });
        } else {
          console.log('oops no result for ', RequestParams);
        }
      })
    

    【讨论】:

    • 它仍然是指最后一个元素。没有工作。
    猜你喜欢
    • 2017-09-08
    • 2020-01-17
    • 1970-01-01
    • 2019-11-12
    • 2023-03-23
    • 1970-01-01
    • 2018-01-31
    • 2021-10-04
    • 2019-12-17
    相关资源
    最近更新 更多