非组件类

时间:2018-12-25 08:04:04

标签: javascript reactjs

我可以在react中定义一个非组件类吗? 我正在尝试定义一个用于管理api请求的类,但无法配置字段(我在BaseUrl值上收到未定义的错误)

class fetchFromAPI {

  constructor(){       
    //super();
    this.BaseURL = "myUrlvalue";
  }
  fetchConfig (payload){
    return  {
      method: 'POST',
      body: JSON.stringify(payload),
      mode: 'cors',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      }          
    };
  }
  fetchUse (/*componentThis,*/command,options){
        var fullUrl = this.BaseURL+command;
        return fetch(fullUrl, this.fetchConfig(options));
  }    
  fetchResponse (data,onSucessFunc,onSucessJson,onFailureFunc,onFailureJson){
    if(data.response==1){
        onSucessFunc(data,onSucessJson);   
    }
    else{
        onFailureFunc(data,onFailureJson);
    }
  }
}
export default fetchFromAPI;

我使用课程的方式

class App extends React.Component{
  constructor(props){
    super(props);
    const payload = {
        sender: "senderId"
      };
    var myAPI = new fetchFromAPI();
    var myRequest = myAPI.fetchConfig(payload); 
    var response = myAPI.fetchUse("api_command",myRequest);        

  }
  render(){
     return (<div></div>);
  }
}

0 个答案:

没有答案