2017-09-16 40 views
0

我是一名專注於前端開發的學生,主要是React和JavaScript。我現在遇到了問題,我正在使用axios,但將來還會有像axios這樣更靈活的其他庫。每次在動作創作者中,我都厭倦了寫一個axios調用。我想爲我的API方法編寫一個可重用組件,就像我可以將它們拖到我的reducer文件中一樣來使用它。當我想改變它時,我沒有通過我所有的組件去改變axios.get如何爲axios.get和axios.post編寫可重用組件?

import Axios from 'axios' 


export function GetApiData() { 
     return function() { 
      Axios.get('/api').then(response=>{ 
       console.log(response.data); 
      }); 
     } 
    } 

我聽說在生產環境中,公司使用可重用組件來處理這種情況。我正在尋找一個可重複使用的組件,如下所示:

import {get, post} from 'some file' 

// code using get or post to make an axios call 

並使用那些獲取,而不是Axios.get。我很難創建可重用的組件。

+0

你可以有一個「幫手」 folder.Where你可以做所有的API調用,然後導出你喜歡做的其他出口 – Debabrata

+0

我是無法用專業的方式寫出來。我正在寫一個簡單的javascript函數,但他們不如其他人。 –

+0

雖然我已經試過像導出功能GET(){在這裏寫一個代碼,但它不是不能正常工作} –

回答

0
在src目錄

你可以創建你喜歡的任何名稱的文件夾,裏面創建另一個js文件的任意名稱like.After是這樣做this.check如果這是你想要的
注:片段不會run.this僅用於演示

const Client={ 
 
    login:(phone,key)=>{ 
 
     //here change it to your desired function like axios.get or anything 
 
     return fetch(
 
      `https://example.com/api/account/login`, 
 
      { 
 
       method:'POST', 
 
       accept:'application/json', 
 
      } 
 
     ).then((response)=>response.json()); 
 
    }, 
 
    //write bunch of methods like the above 
 

 
} 
 

 

 

 
export default Client;

導入它,無論你想用它it.Use並告訴我,如果有任何問題發生

說你想在文件 使用它,你可以做

import Client from "yourfoldername/filename"; 


//call to client 
// i believe your api call returns a promise 
Client.login(parameters).then((res)=>{ 
     //do something here 
    } 
).catch(err=>{ 
    //do something here 
})