【问题标题】:Lessen Duplication of Dispatching in React/Redux减少 React/Redux 中的调度重复
【发布时间】:2022-01-03 11:12:54
【问题描述】:

我有一个名为saveThing 的操作。在其中,我有参数 thingNoErrorsthingWithErrors 。我有一个if statement,如果thingNoErrors 有一个值,那么您只需调用API。我的问题是我不想重复发送constants.SUCCESSFULcallback 只是为了减少代码并避免重复。有没有更好的修改方法?

export const saveThing =
  ({ thingNoErrors = [], thingWithErrors = [], callback = () => {} }) =>
  async (dispatch) => {
    try {
      dispatch({
        type: constants.REQUESTING,
      });

      if (thingNoErrors?.length > 0) {
        let formData = new FormData();

        Object.keys(thingNoErrors).forEach((fieldName) => {
          formData.append(
            thingNoErrors[fieldName]?.name,
            thingNoErrors[fieldName]?.file
          );
        });

        const response = await axios.post(`${API_URL}/sample/api`, formData);

        dispatch({
          type: constants.SUCCESSFUL,
          payload: {
            data: [...response.data, ...thingWithErrors],
          },
        });

        callback('success')
      }

      dispatch({
        type: constants.SUCCESSFUL,
        payload: {
          data: thingWithErrors,
        },
      });

      callback('success')
    } catch (error) {
      dispatch({
        type: constants.ERROR,
      });
    }
  };

【问题讨论】:

    标签: reactjs redux ecmascript-6 react-hooks


    【解决方案1】:

    您可以将“响应”变量分解/声明为 if 条件块之外,并将其浅合并到 data 数组中,以允许单个成功的操作调度。

    export const saveThing = ({
      thingNoErrors = [],
      thingWithErrors = [],
      callback = () => {},
    }) => async (dispatch) => {
      try {
        dispatch({ type: constants.REQUESTING });
    
        let response;
    
        if (thingNoErrors?.length) {
          let formData = new FormData();
    
          Object.keys(thingNoErrors).forEach((fieldName) => {
            formData.append(
              thingNoErrors[fieldName]?.name,
              thingNoErrors[fieldName]?.file
            );
          });
    
          response = await axios.post(`${API_URL}/sample/api`, formData);
        }
    
        dispatch({
          type: constants.SUCCESSFUL,
          payload: {
            data: [...(response?.data || []), ...thingWithErrors],
          },
        });
    
        callback('success');
      } catch (error) {
        dispatch({ type: constants.ERROR });
      }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 2018-05-05
      • 2021-08-04
      • 2020-10-17
      • 2017-08-09
      • 1970-01-01
      相关资源
      最近更新 更多