将不需要't映射到状态

Where to put functions that don't map to state?

本文关键字:映射 状态 不需要      更新时间:2023-09-26

React/Redux n00b这里:)-使用一个糟糕的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

您可以根据promise是否得到解决来调度不同的操作。最简单的方法是这样的:

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));
    });
}

这里有更多关于如何做这种事情的文档。。。

相关文章: