如何将提取功能放在单独的文件中?

时间:2019-05-13 15:10:49

标签: reactjs fetch

所以我想在单独的文件中获取请求。仅用于测试。然后在componentDidMount中调用它。我仍然不确定。正确的做法是什么?

这是我的功能:

    const fetchNewWord = () => {
  fetch("https://wordsapiv1.p.rapidapi.com/words/?lettersMax=11&random=true", {
    headers: {
      "X-Rapidapi-Host": "wordsapiv1.p.rapidapi.com",
      "X-Rapidapi-Key": "myKey"
    }
  })
    .then(data => data.json())
    .then(data => {
      return data.word;
    });
};

export default fetchNewWord;

2 个答案:

答案 0 :(得分:0)

您将return的提取回调结果作为函数的响应:

export const fetchNewWord = () => {
  return fetch("https://wordsapiv1.p.rapidapi.com/words/?lettersMax=11&random=true", {
    headers: {
      "X-Rapidapi-Host": "wordsapiv1.p.rapidapi.com",
      "X-Rapidapi-Key": "myKey"
    }
  })
  .then(data => data.json())
  .then(data => data.word);
};

执行const data = fetchNewWord(); console.log(data);后,您将看到结果。

答案 1 :(得分:0)

您可以创建一个单独的服务来获取代码,并将其用作独立的提供程序

这是 httpRequest.js ,您可以使用默认的提取API:

import axios from 'axios';

class HttpRequest {
  constructor(baseURL) {
    this.axios = axios.create({
      baseURL,
    });
  }

  reponseInterceptor() {
    // Add a response interceptor
    this.axios.interceptors.response.use(
      response => (
        // Do something with response data
        response
      ),
      error => (
        // Do something with response error
        Promise.reject(error)
      ),
    );
  }

  requsetInterceptor() {
    this.axios.interceptors.request.use(
      config => (
        // Do something before request is sent
        config),
      error => (
        // Do something with request error
        Promise.reject(error)
      ),
    );
  }

  fetch(url, params, config = {}) {
    return this.axios.get(url, {
      params,
      ...config,
    });
  }

  create(url, data, config = {}) {
    return this.axios.post(url, data, {
      ...config,
    });
  }

  update(url, data, config = {}) {
    return this.axios.put(url, data, {
      ...config,
    });
  }

  patch(url, data, config = {}) {
    return this.axios.patch(url, data, {
      ...config,
    });
  }

  remove(url, params, config = {}) {
    return this.axios.delete(url, {
      params,
      ...config,
    });
  }
}

export default HttpRequest;

您可以在此处创建 words.js 服务:

import config from 'config';
import HttpRequest from './httpRequest';

export default class WordService extends HttpRequest {
  constructor(servicePath) {
    super(config.markMeHost);
    this.path = `${config.markMeHost}/${servicePath}`;
  }

  listWords() {
    return this.fetch(this.path, {});
  }

  createWords(data) {
    return this.create(this.path, data);
  }

  updateWords(data, id) {
    return this.update(`${this.path}/${id}`, data);
  }

  deleteWords(id) {
    return this.remove(`${this.path}/${id}`);
  }
}

您的api服务 index.js

import WordService from './words';

// Give arg to provider to start endpoint with specific path for example = abc.com/api/words
export default new WordService('words');

有关更多详细信息,您可以检查我的github帐户中的axios服务https://github.com/m-nathani/markme/tree/master/frontend/src/service/api