2017-10-14 44 views
1

我試圖將axios函數分離到單獨的服務層。請建議如何在反應js中做到這一點?react js - 如何做服務層調用

``` 
class xxx extends Component { 
constructor(props) { 
    super(props) 
    this.state = { 
     ownerName: '', 
    } 
    this.handleKeyUp = this.handleKeyUp.bind(this) 
} 

handleKeyUp(e) { 
    if (e.target.value.length > 4) { 
     var self = this 
     axios.get(`/https://exampleService.com/${e.target.value}`) 
      .then(function (response) { 
       self.setState({ownerName: response.data['name']}) 
      }) 
      .catch(function (error) { 
       if (error.response) { 
        if (error.response.status === 404) { 
         self.setState({ownerName: `\u2014`}) 
        } 
       } 
      }) 
    } 
} 

render() { 
    return (
     <div> 
      <Input OnKeyUp={(event) => this.handleKeyUp(event)} ></Input> 
     </div> 
    ); 
} 
} 
``` 

我試圖分開像下面使用module.exports,但我無法從模塊組件的輸出,並把它傳遞給的xxx組件。

``` 
module.exports = { 
    axios.get ...... 
    ..... 
} 

``` 

回答

3

您可以創建一個名爲Api的類,並在該類中創建一個可以執行axios調用的函數。該函數應該接受一個回調函數,您可以使用該回調函數來設置組件中的狀態。

export default class Api{ 

    function DoAxiosCall(callback){ 
    axios.get(`/https://exampleService.com/${e.target.value}`) 
       .then(function (response) { 
        callback(response.data['name']); 
       }) 
       .catch(function (error) { 
        if (error.response) { 
         if (error.response.status === 404) { 
          callback(`\u2014`) 
         } 
        } 
       }) 
    } 
} 

從你的組件,你可以導入API類,創建它的一個實例,然後調用它處理Axios的調用函數,傳遞,處理更新狀態回調函數。

import Api from './path/to/Api'; 
.... 
class xxx extends Component { 
constructor(props) { 
    super(props) 
    this.state = { 
     ownerName: '', 
    } 
    this.handleKeyUp = this.handleKeyUp.bind(this) 
    this.api = new Api(); 
} 

updateState =(newOwner)=> this.setState({ownerName:newOwner}) 

handleKeyUp(e) { 
    if (e.target.value.length > 4) { 
     this.api.DoAxiosCall(this.updateState); 
    } 
} 

render() { 
    return (
     <div> 
      <Input OnKeyUp={(event) => this.handleKeyUp(event)} ></Input> 
     </div> 
    ); 
} 
} 
+0

謝謝!它工作得很好 – user7700138

2

您可以像下面那樣創建服務模塊。

// service.js 

'use strict'; 

const axios = require('axios'); 

const getOwner = (url) => axios.get(url) 
.then(response => response.data['name']) 
.catch((error) => { 
    if (error.response && error.response.status === 404) { 
      return `\u2014`; 
    }; 
}); 

module.exports = { 
getOwner 
} 

現在,您可以通過要求在您的xxx組件中使用此getOwner函數。

// xxx component 

const {getOwner} = require('path of service.js'); 
.... 
.... 
handleKeyUp(e) { 
if (e.target.value.length > 4) { 
    return getOwner(`https://exampleService.com/${e.target.value}`) 
     .then(response => this.setState({ownerName: response})) 
} 
} 
... 
... 
+0

謝謝!這個選項太棒了! – user7700138