如何在React

时间:2017-12-12 09:29:46

标签: ajax reactjs

我在组件中有两个类似的功能:

getSavedSearches() {
  $.ajax({
    url: '/api/v2/saved_searches',
    type: 'get',
    dataType: 'json',
    data: {
      manually: true,
      per: 4
    },
    success: (files) => {
      const savedSearches = files;
      this.setState({
        savedSearches
      })
    },
    error: (xhr, status, error) => {
      console.log('Saved searches error: ', error);
    }
  })
}

getRecentSearched() {
  $.ajax({
    url: '/api/v2/saved_searches',
    type: 'get',
    data: {
      manually: false,
      per: 4
    },
    success: (files) => {
      const recentSearched = files
      this.setState({
        recentSearched
      })
    },
    error: (xhr, status, error) => {
      console.log('Saved searches error: ', error);
    }
  })
}

如何重构这些功能以避免重复?

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

编写api调用的常用方法,并在该函数中将url,callback方法作为参数传递。使用该回调方法将数据返回到原点。

像这样:

getSavedSearches() {
  apiCall('/api/v2/saved_searches', files => {
    const savedSearches = files;
    this.setState({
      savedSearches
    })
  })
}

getRecentSearched() {
  apiCall('/api/v2/saved_searches', files => {
    const recentSearched = files
    this.setState({
      recentSearched
    })
  })
}

api呼叫的常用方法:

apiCall(url, callback){
  $.ajax({
    url: url,
    type: 'get',
    data: {
      manually: false,
      per: 4
    },
    success: (files) => {
      callback(files)
    },
    error: (xhr, status, error) => {
      console.log('Saved searches error: ', error);
    }
  })
}

建议:我们也可以通过在参数中传递方法和数据来使api调用函数更通用。

像这样:

apiCall(url, type, data, callback){
    $.ajax({
      url: url,
      type: type,
      data: data,
      success: (files) => {
        callback(files)
      },
      error: (xhr, status, error) => {
        console.log('Saved searches error: ', error);
      }
    })
}

答案 1 :(得分:1)

您可以将“请求”抽象为(例如axios):

import axios from 'axios';
import { API } from '../../constants';


const sessionString = localStorage.getItem('session');
let auth;
if (sessionString) {
  const session = JSON.parse(sessionString);
  auth = `${session.nation}|${session.user}|${session.token}`;
}
/**
 * Create an Axios Client with defaults
 */
const client = axios.create({
  baseURL: API.BASEURL,
  headers: { Authorization: auth },
});

/**
 * Request Wrapper with default success/error actions
 */
    const request = (options) => {
    const onSuccess = (response) => {
    console.debug('Request Successful!', response);
    // If options.raw is true, return all response
    return options.raw ? response : response.data;
  };

  const onError = (error) => {
    console.error('Request Failed:', error.config);

    if (error.response) {
      // Request was made but server responded with something
      // other than 2xx
      console.error('Status:', error.response.status);
      console.error('Data:', error.response.data);
      console.error('Headers:', error.response.headers);
    } else {
      // Something else happened while setting up the request
      // triggered the error
      console.error('Error Message:', error.message);
    }

    return Promise.reject(error.response || error.message);
  };

  return client(options)
            .then(onSuccess)
            .catch(onError);
};

export default request;

然后在课堂上使用:

const getMethod = (page) => request(
  {
    url: API.YOURAPI,
    method: 'GET',
    params: {
      page: page || 1,
   },
  });