【发布时间】:2018-11-27 12:48:00
【问题描述】:
我正在使用 ReactJS 高阶函数来增强现有组件的 API 获取能力以及加载、错误视图。为了变得更加可重用,我希望另一个使用我的 HOC 的程序员能够添加自定义加载,像这样的错误视图。
var FetchTest = fetchableContainer({
url:"https://jsonplaceholder.typicode.com/posts",
loadingView: <div>..Custom Loading..</div>,
noConnectionView: <div>.. Custom no connection view .. </div>,
errorView: <div>Custom Error View</div>
})(TestComponent);
不幸的是,它显示错误消息。
元素类型无效:应为字符串(用于内置组件) 或类/函数(用于复合组件)但得到:对象。
谁能告诉我另一个代码简洁优雅的解决方案。这是我的 fetchableContainer。
import React, {Component} from 'react';
import axios from 'axios';
import loadingView from './loadingView.js';
import errorView from './errorView.js';
import noDataView from './noDataView.js';
import noConnectionView from './noConnectionView.js';
//redux imports
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import { Link } from 'react-router';
const fetchableContainer = (json) => (BaseComponent) => {
let url = json.url || "";
let loadingView = json.loadingView || loadingView;
let errorView = json.errorView || errorView;
let noConnectionView = json.noConnectionView || noConnectionView;
let noDataView = json.noDataView || noDataView;
class FetchableContainer extends React.Component{
constructor(props){
super(props);
this.state = {
fetchData: null,
loading: false,
fetchError: null,
interntConnection: navigator.onLine?true:false,
};
}
componentDidMount(){
this.setState({loading: true});
axios.get(this.url,{
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 <this.noConnectionView/>;
}
if(this.state.loading){
return <this.loadingView/>;
}
if(this.state.fetchError){
return <this.errorView/>;
}
return (
<BaseComponent {...this.props}{...this.state}/>
);
}
}
}
export default fetchableContainer;
【问题讨论】:
标签: reactjs higher-order-functions higher-order-components