Javascript 如何在外部函数中使用setState?
我已经在外部文件中为Javascript 如何在外部函数中使用setState?,javascript,reactjs,Javascript,Reactjs,我已经在外部文件中为api调用创建了函数。如何访问外部文件中的函数/setState import Request from 'superagent'; const getApi = () => { let url = '/* URL */'; return Request.get(url).then((res) => { this.setState({ content: res.body }); }
api调用创建了函数
。如何访问外部文件中的函数/setState
import Request from 'superagent';
const getApi = () => {
let url = '/* URL */';
return Request.get(url).then((res) => {
this.setState({
content: res.body
});
});
}
export default getApi;
我收到这个错误:
'TypeError:无法读取未定义的'setState'属性'
您可以从组件向getApi
函数传递回调
componentWillMount(){
getApi();
}
组件
const getApi = (onSuccess) => {
let url = '/* URL */';
return Request.get(url).then((res) => {
onSuccess(res.body);
});
}
注意。随着项目规模的扩大,您可能希望查看状态管理系统,例如Redux。从技术上讲,您可以将实例传递给getApi
,以便它知道这个应该是什么。但在我看来,这是一个糟糕的方法。它会产生不必要的依赖关系。目前,getApi()
需要知道React类是如何工作的;该函数负责正确操作实例的状态
如果getApi()
只返回值,而实例使用该值,则更好:
componentWillMount(){
getApi(this.setApiResponse);
}
setApiResponse(data) {
this.setState({
content: data
});
}
我的解决方案:
const getApi = () => {
let url = '/* URL */';
return Request.get(url).then(res => res.body);
}
componentWillMount(){
getApi().then(content => this.setState({ content }));
}
将回调方法
传递到getApi()
方法中并调用该方法的可能重复项一旦得到响应,请在该回调方法中执行setState。如果不能,则需要返回响应,然后在应该读取的函数中设置state
function getApi(component) {
let url = '/* url */';
return Request.get(url).then((res) => {
component.setState({
content: res.body,
});
});
}
componentWillMount(){
getApi(this);
}