我试图将下面的axios功能隔离到一个单独的服务层。请建议如何在 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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我试图像下面一样使用 分离module.exports,但我无法从模块组件中获取输出并将其传递给 xxx 组件。
module.exports = {
axios.get ......
.....
}
Run Code Online (Sandbox Code Playgroud)
您可以创建一个名为 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`)
}
}
})
}
}
Run Code Online (Sandbox Code Playgroud)
从您的组件中,您可以导入 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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以像下面一样创建服务模块。
// 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
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以通过 require 在 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}))
}
}
...
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15742 次 |
| 最近记录: |