withLoader
语法
编辑 hoc
import React from 'react';
interface LoaderState {
data: any;
loading: boolean;
}
interface LoaderProps {
data: any;
}
const withLoader = <P extends LoaderState>(
WrappedComponent: React.ComponentType<P>,
url: string,
) =>
class LoaderComponent extends React.Component<LoaderProps, LoaderState> {
constructor(props: any) {
super(props);
this.state = {
data: null,
loading: false,
};
}
componentDidMount() {
this.setState({
loading: true,
});
const ajax = new XMLHttpRequest();
ajax.open('get', url, true);
ajax.onreadystatechange = () => {
if (ajax.readyState === 4 && [200, 304].includes(ajax.status)) {
const {response} = ajax;
const data = JSON.parse(response);
this.setState({
data,
loading: false,
});
}
};
ajax.send();
}
render() {
const {data, loading} = this.state;
return (
<div>
{loading || !data ? (
<h3>正在请求数据……</h3>
) : (
<WrappedComponent {...(this.props as P)} data={data} />
)}
</div>
);
}
};
export default withLoader;
使用 hoc
import React from 'react';
import withLoader from './hocs/withLoader';
const App: React.FC<{data: any[]}> = (props) => {
const {data} = props;
return (
<div>
<div>{data.length}</div>
</div>
);
};
export default withLoader(
App,
'https://api.github.com/repos/bolawen/template/branches',
);