import Request from 'superagent';
const getApi = () => {
let url = '/* URL */';
return Request.get(url).then((res) => {
this.setState({
content: res.body
});
});
}
export default getApi;
我已经在api call
的外部文件中创建了function
。如何在外部文件中访问function/setState
?
componentWillMount(){
getApi();
}
我收到此错误:
'typeError:无法读取未定义的'setState'
您可以从组件中传递到getApi
函数的回调。
const getApi = (onSuccess) => {
let url = '/* URL */';
return Request.get(url).then((res) => {
onSuccess(res.body);
});
}
组件
componentWillMount(){
getApi(this.setApiResponse);
}
setApiResponse(data) {
this.setState({
content: data
});
}
nb。随着您的项目增长,您可能希望研究一个状态管理系统,例如Redux。
从技术上讲,您可以将实例传递给getApi
,以便知道this
应该是什么。但是IMO。那是一个糟糕的方法。它创造了不必要的依赖性。目前,getApi()
需要知道React类的工作方式。该功能负责正确操纵实例的状态。
如果getApi()
仅返回值,并且实例消耗了它:
const getApi = () => {
let url = '/* URL */';
return Request.get(url).then(res => res.body);
}
componentWillMount(){
getApi().then(content => this.setState({ content }));
}
我的解决方案:
function getApi(component) {
let url = '/* url */';
return Request.get(url).then((res) => {
component.setState({
content: res.body,
});
});
}
componentWillMount(){
getApi(this);
}