2017-10-14 15 views
1

私は別のサービス層にaxiosの機能の下に分離しようとしています。 Plsは反応するjsでこれを行う方法を提案しますか?反応するjs - How to doサービス層の呼び出し

``` 
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のコンポーネントにそれを渡すことができないんです。

答えて

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

関連する問題