我刚刚发现了错误。这是因为我正在传递JSX组件并试图获取该JSX组件。通过传递返回JSX组件的函数并在FetchableContainer的render方法上获取该函数,可以解决此错误,如下所示。
var FetchTest = fetchableContainer({
url: 'https://jsonplaceholder.typicode.com/posts/',
errorView: ()=> <div>Custom Error View</div>,
LoadingView:()=><div>Custom loading</div> ,
NoConnectionView: ()=> <div>Custom no Connection</div>
})(TestComponent);
FetchableContainer的最终代码如下所示。
import React, {Component} from 'react';
import axios from 'axios';
import LoadingView from './LoadingView';
import ErrorView from './ErrorView';
import NoDataView from './NoDataView';
import NoConnectionView from './NoConnectionView';
//redux imports
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import { Link } from 'react-router';
const fetchableContainer = (json) => (BaseComponent) =>{
let LoadingFetchView = json.LoadingView || LoadingView;
let fetchUrl = json.url || "https://jsonplaceholder.typicode.com/posts/";
let ErrorFetchView = json.ErrorView || ErrorView;
let NoConnectionFetchView = json.NoConnectionView || NoConnectionView;
let NoDataFetchView = json.NoDataView || NoDataView;
class FetchableContainer extends React.Component{
constructor(props){
console.log("inside constructure");
console.log(LoadingView);
super(props);
this.state = {
fetchData: null,
loading: false,
fetchError: null,
interntConnection: navigator.onLine?true:false,
};
}
componentDidMount(){
this.setState({loading: true});
axios.get(fetchUrl,{
headers: {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
}
}).then((response)=>{
this.setState({fetchData: response.data});
this.setState({loading: false});
}).catch((error)=>{
console.log("Erorr happen");
console.log(error);
this.setState({fetchError: error});
});
}
render(){
if(!this.state.interntConnection){
return <NoConnectionFetchView/>;
}
if(this.state.loading){
return <LoadingFetchView/>;
}
if(this.state.fetchError){
return <ErrorFetchView/>;
}
return (
<BaseComponent {...this.props}{...this.state}/>
);
}
}
return FetchableContainer;
}
export default fetchableContainer;