我从 Reactjs create-react-app 项目运行了一些测试。
我不明白为什么 SimpleSpreadsheet.xlsx 文件没有正确加载,而response
fromXMLHttpRequest()
只是别的东西。
看看这里的图像,它responseURL
是一个 XLSX 文件:
'http://localhost:6545/images/weeks/1/SimpleSpreadsheet.xlsx'
该文件的位置是Public
create-react-app 项目中的文件夹。这就像fetch
开始然后突然因为response
你看到的确实有类似的 XLSX 格式
这是执行以下操作的组件fetch
:
import React, { Component } from 'react';
import Error from './error';
import Loading from './loading';
function WithFetching(WrappedComponent) {
return class FetchComponent extends Component {
constructor(props) {
// eslint-disable-line no-shadow
super(props);
this.state = {};
this.xhr = this.createRequest(props.newProps.filePath);
}
componentDidMount() {
try {
this.fetch();
} catch (e) {
if (this.props.onError) {
this.props.onError(e);
}
this.setState({ error: 'fetch error' });
}
}
componentWillUnmount() {
this.abort();
}
createRequest(path) {
let xhr = new XMLHttpRequest();
if ('withCredentials' in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open('GET', path, true);
// } else if (typeof XDomainRequest !== 'undefined') {
// // XDomainRequest for IE.
// xhr = new XDomainRequest();
// xhr.open('GET', path);
} else {
// CORS not supported.
xhr = null;
return null;
}
if (this.props.responseType) {
xhr.responseType = this.props.responseType;
}
xhr.onload = () => {
if (xhr.status >= 400) {
this.setState({ error: `fetch error with status ${xhr.status}` });
return;
}
const resp = this.props.responseType ? xhr.response : xhr.responseText;
this.setState({ data: resp });
};
return xhr;
}
fetch() {
this.xhr.send();
}
abort() {
if (this.xhr) {
this.xhr.abort();
}
}
render() {
if (!this.xhr) {
return <h1>CORS not supported..</h1>;
}
if (this.state.error) {
return <Error {...this.props} error={this.state.error} />;
}
if (this.state.data) {
return <WrappedComponent data={this.state.data} {...this.props} />;
}
return <Loading />;
}
};
}
export default WithFetching;
XLSX 文件如下所示: