2017-10-14 49 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