【问题标题】:cancel previous request live search reactjs取消之前的请求实时搜索reactjs
【发布时间】:2018-06-15 19:03:53
【问题描述】:

我需要使用实时搜索 axios 请求取消上一个请求 - 我正在使用油门去抖动来发出请求,但是当现有单词被删除并更新新值时我遇到了问题 - 结果显示为前一个单词在某些情况下,我认为我需要取消所有先前对同一 requestID 的请求,通读文章,但它们都不适合我的用例。任何帮助都是我的代码。

减速器:

switch (action.type) {
case GETTING_DATA:
  return {
    ...state,
    results: action.payload,
  };
case SEARCH_DATA:
  return {
    ...state,
    Results: action.payload,
  };



export function getSearch(value) {
  return (dispatch) => {
    dispatch({
      type: GETTING_DATA,
    });
    const arg = {
      search: value,
    };
    apiGet('abc', arg).then(response => 
     getResults(dispatch, response));
  };
}
const getResults = (dispatch, response) => {
  dispatch({
    type: SEARCH_DATA,
    payload: response.data,
  });
};

服务:

export const apiGet = async (path = '', args = {}) => {
  const endpoint = "/aaa/aaa/aaa";
  try {
    return axios.get(endpoint, getConfig());
  } catch (e) {
  }
};

【问题讨论】:

    标签: react-redux axios debounce


    【解决方案1】:

    尝试以下方法:

    value 作为负载传递给GETTING_DATA 操作。这将在状态中存储最新请求的值。

    然后,在getResults 中将相同的值与响应数据一起发送到reducer。在 reducer 内部,检查从 getResults 传递的值是否与通过 GETTING_DATA 存储在 state 中的值相同。

    如果是这样,则此数据是响应最新请求而来的,因此您希望将其存储在状态中。否则,您可以忽略它。

    换句话说:

    行动:

    switch (action.type) {
    case GETTING_DATA:
      return {
        ...state,
        lastRequestTime: action.payload,
      };
    case SEARCH_DATA:
      if (action.payload.lastRequestTime === state.lastRequestTime) {
        return {
          ...state,
          Results: action.payload.response,
        };
      } else {
        return state
      }
    

    行动:

    export function getSearch(value) {
      return (dispatch) => {
        const lastRequestTime = Date.now()
        dispatch({
          type: GETTING_DATA, 
          payload: lastRequestTime
        });
        const arg = {
          search: value,
        };
        apiGet('abc', arg).then(response => 
         getResults(dispatch, { response, lastRequestTime }));
      };
    }
    const getResults = (dispatch, response) => {
      dispatch({
        type: SEARCH_DATA,
        payload: response.data,
      });
    };
    

    【讨论】:

    • 不明白如何在我的代码中使用它,尤其是如何在操作中触发取消方法 - 它是否应该来自组件..?
    • 尝试以下操作:将value 作为有效负载传递给GETTING_DATA 操作。这将在状态中存储最新请求的值。然后在getResults 中将相同的值与响应数据一起发送到reducer,并在reducer 内部检查从getResults 传递的value 是否与通过GETTING_DATA 存储在状态中的相同。如果没有,您可以忽略数据。否则,这是您要存储在状态中的数据。
    • @jacekhttps://stackoverflow.com/users/1967872/jacek-lampart - 感谢您的回复 - 我尝试在 GETTING_DATA 中传递值 - 我如何从状态(当前状态)中获取值) - 我已经用我的 reducer 代码更新了我的问题 - 你介意按照你所说的更新它吗
    • stackoverflow.com/users/1967872/jacek-lampart..?您能否用您所说的更新我的代码 - 尝试但无法获取状态并且不确定如何在减速器中进行比较
    【解决方案2】:

    您可以创建这样一个小助手包装器,并在需要取消先前请求的任何地方使用它:

    // ../services.js
    
    function createApi(baseURL) {
      const axiosInst = axios.create({
        baseURL,
      });
      // here you can set default headers:
      axiosInst.defaults.headers.common['Content-Type'] = 'application/json';
      // return the function with closure variable to use for canceling
      return (type = 'get') => {
        let call = null;
        return (url, data, config) => {
          if (call) {
            call.cancel('Only one request allowed!');
          }
          call = axios.CancelToken.source();
          const extConf = {
            cancelToken: call.token,
            ...config,
          };
          switch (type) {
            case 'request':
              return api[type](extConf);
    
            case 'get':
            case 'delete':
            case 'head':
              return api[type](url, extConf);
    
            default:
              return api[type](url, data, extConf);
          }
        };
      };
    }
    
    export const baseApi = createApi('http://localhost:5000/api/')

    然后像这样在任何地方使用它:

    import baseApi from '../servises.js';
    
    const fetchItemsService = baseApi('post');
    
    //...
    componentDidMount() {
      fetchItemsService('/items').then(() => {});
    }
    //...

    【讨论】:

      猜你喜欢
      • 2019-09-14
      • 1970-01-01
      • 2016-12-29
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      • 2017-08-11
      • 2020-06-23
      • 2013-08-03
      相关资源
      最近更新 更多