【问题标题】:Where to put functions that don't map to state?将不映射到状态的函数放在哪里?
【发布时间】:2016-01-04 19:00:44
【问题描述】:

React/Redux n00b here :) - 使用无法正确返回错误代码的糟糕 API(即使端点关闭也返回 200),因此会打乱我的 Ajax 调用。 API 的所有者将无法尽快更正此问题,因此我现在必须解决它。

我目前正在检查每个 success 类似这样的东西(使用 lodash):

success: function(data) {
    // check if error is REALLY an error
    if (_.isUndefined(data.error) || _.isNull(data.error)) {
        if (data.id) data.sessionId = data.id;
            if (data.alias) data.alias = data.alias;
              resolve(data || {});
    } else {
        reject(data); // this is an error
    }
 }

我想将它移到它自己的函数中,以便我可以将它用于执行 Ajax 调用的任何操作,但我不确定在哪里包含它。

这种类型的函数应该映射到状态(因此,将其视为一个动作并构建一个 reducer)还是应该是 Redux 之外的通用函数并抛出 main.js

【问题讨论】:

    标签: javascript ajax reactjs redux


    【解决方案1】:

    您可以根据承诺是否已解决来分派不同的操作。最简单的方法是这样的:

    function onSuccess(data) {
      return {
        type: "FETCH_THING_SUCCESS",
        thing: data
      };
    }
    
    function onError(error) {
      return {
        type: "FETCH_THING_ERROR",
        error: error
      };
    }
    
    function fetchThing(dispatch, id) {
      // the ajax call that returns the promise
      fetcher(id)
        .then(function(data){
          dispatch(onSuccess(data));
        })
        .catch(function(error) {
          dispatch(onError(error));
        });
    }
    

    这里还有一些documentation如何做这种事情......

    【讨论】:

      猜你喜欢
      • 2016-03-08
      • 2015-09-05
      • 2013-09-22
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多