【发布时间】:2019-02-07 13:33:06
【问题描述】:
我有服务函数withFetching,它返回类Fetch:
import React from 'react';
import * as axios from 'axios';
const withFetching = url => Component => {
class Fetch extends React.Component {
state = {
data: null,
isLoading: false
};
componentDidMount() {
this.setState({isLoading: true});
}
get = (params) => {
axios.get(url, params)
.then(response => {
this.setState({data: response.data, isLoading: false});
})
.catch(error => {
console.error('%c ERROR', 'color: #FA12D6', error);
});
};
post = data => {}
put = () => {}
render() {
return <Component {...this.state}
{...this.props}
post={this.post}
put={this.put}
delete={this.delete}/>;
}
}
Fetch.displayName = `Fetch(${Component.displayName || Component.name || 'Component'})`;
return Fetch;
};
export default withFetching;
我需要在另一个类中调用方法get。我正在做这样的事情:
import React, { Component } from 'react';
import MyComponent from './MyComponent/index';
import WithFetch from './../../../../services/withFetching';
class TableSources extends Component {
componentWillMount() {
const params = {}
WithFetch('my URL')(MyComponent).get(params)
}
render() {
return (...)
}
}
export default TableSources;
【问题讨论】:
-
您是否使用类组件作为服务?这与用火箭筒射击苍蝇是一样的。将方法作为函数存储在单独的文件中既简单又干净,因此您可以简单地执行 MyService.get(params).then(..)
-
嗨!很高兴看到另一种构建获取服务的方法????你有更多的代码要显示吗?据我所知,有一件事可能不起作用,那就是 get() 方法及其调用方式。挂载该组件后,可以从父级调用非静态的自定义方法。我认为您需要为此提供参考,例如 React 文档中的参考:Forwarding refs from Higher-order Components 如果我们能够进一步完善您的问题,那么答案是可能的,而不仅仅是指导。
标签: javascript reactjs crud